Beispiel #1
0
  bool IpoptInternal::intermediate_callback(const double* x, const double* z_L, const double* z_U, const double* g, const double* lambda, double obj_value, int iter, double inf_pr, double inf_du,double mu,double d_norm,double regularization_size,double alpha_du,double alpha_pr,int ls_trials,bool full_callback) {
    n_iter_ += 1;
    try {
      log("intermediate_callback started");
      if (gather_stats_) {
        Dictionary & iterations = stats_["iterations"];
        static_cast<std::vector<double> &>(iterations["inf_pr"]).push_back(inf_pr);
        static_cast<std::vector<double> &>(iterations["inf_du"]).push_back(inf_du);
        static_cast<std::vector<double> &>(iterations["mu"]).push_back(mu);
        static_cast<std::vector<double> &>(iterations["d_norm"]).push_back(d_norm);
        static_cast<std::vector<double> &>(iterations["regularization_size"]).push_back(regularization_size);
        static_cast<std::vector<double> &>(iterations["alpha_pr"]).push_back(alpha_pr);
        static_cast<std::vector<double> &>(iterations["alpha_du"]).push_back(alpha_du);
        static_cast<std::vector<int> &>(iterations["ls_trials"]).push_back(ls_trials);
        static_cast<std::vector<double> &>(iterations["obj"]).push_back(obj_value);
      }
      double time1 = clock();
      if (!callback_.isNull()) {
        if(full_callback) {
          if (!output(NLP_SOLVER_X).isEmpty()) copy(x,x+nx_,output(NLP_SOLVER_X).begin());
        
          vector<double>& lambda_x = output(NLP_SOLVER_LAM_X).data();
          for(int i=0; i<lambda_x.size(); ++i){
            lambda_x[i] = z_U[i]-z_L[i];
          }
          if (!output(NLP_SOLVER_LAM_G).isEmpty()) copy(lambda,lambda+ng_,output(NLP_SOLVER_LAM_G).begin());
          if (!output(NLP_SOLVER_G).isEmpty()) copy(g,g+ng_,output(NLP_SOLVER_G).begin());
        } else {
          if (iter==0) {
            cerr << "Warning: intermediate_callback is disfunctional in your installation. You will only be able to use getStats(). See https://github.com/casadi/casadi/wiki/enableIpoptCallback to enable it." << endl;
          }
        }
        
        Dictionary iteration;
        iteration["iter"] = iter;
        iteration["inf_pr"] = inf_pr;
        iteration["inf_du"] = inf_du;
        iteration["mu"] = mu;
        iteration["d_norm"] = d_norm;
        iteration["regularization_size"] = regularization_size;
        iteration["alpha_pr"] = alpha_pr;
        iteration["alpha_du"] = alpha_du;
        iteration["ls_trials"] = ls_trials;
        iteration["obj"] = obj_value;
        stats_["iteration"] = iteration;

        output(NLP_SOLVER_F).at(0) = obj_value;

        int ret = callback_(ref_,user_data_);
        
        double time2 = clock();
        t_callback_fun_ += double(time2-time1)/CLOCKS_PER_SEC;
        return  !ret;
      } else {
        return 1;
      }
    } catch (exception& ex){
      if (getOption("iteration_callback_ignore_errors")) {
        cerr << "intermediate_callback: " << ex.what() << endl;
      } else {
        throw ex;
      }
      return 1;
    }
  }
QSizeF QgsLayerTreeModelLegendNode::drawSymbolText( const QgsLegendSettings& settings, ItemContext* ctx, QSizeF symbolSize ) const
{
  QSizeF labelSize( 0, 0 );

  QFont symbolLabelFont = settings.style( QgsComposerLegendStyle::SymbolLabel ).font();
  double textHeight = settings.fontHeightCharacterMM( symbolLabelFont, QChar( '0' ) );

  QStringList lines = settings.splitStringForWrapping( data( Qt::DisplayRole ).toString() );

  labelSize.rheight() = lines.count() * textHeight + ( lines.count() - 1 ) * settings.lineSpacing();

  double labelX = 0.0, labelY = 0.0;
  if ( ctx )
  {
    ctx->painter->setPen( settings.fontColor() );

    labelX = ctx->point.x() + qMax( static_cast< double >( symbolSize.width() ), ctx->labelXOffset );
    labelY = ctx->point.y();

    // Vertical alignment of label with symbol
    if ( labelSize.height() < symbolSize.height() )
      labelY += symbolSize.height() / 2 + textHeight / 2;  // label centered with symbol
    else
      labelY += textHeight; // label starts at top and runs under symbol
  }

  for ( QStringList::Iterator itemPart = lines.begin(); itemPart != lines.end(); ++itemPart )
  {
    labelSize.rwidth() = qMax( settings.textWidthMillimeters( symbolLabelFont, *itemPart ), double( labelSize.width() ) );

    if ( ctx )
    {
      settings.drawText( ctx->painter, labelX, labelY, *itemPart, symbolLabelFont );
      if ( itemPart != lines.end() )
        labelY += settings.lineSpacing() + textHeight;
    }
  }

  return labelSize;
}
Beispiel #3
0
/*************************************************************************
One ASA iteration

Called after initialization with MinASACreate.
See HTML documentation for examples.

INPUT PARAMETERS:
    State   -   structure which stores algorithm state between calls and
                which is used for reverse communication. Must be initialized
                with MinASACreate.
RESULT:
* if function returned False, iterative proces has converged.
  Use MinLBFGSResults() to obtain optimization results.
* if subroutine returned True, then, depending on structure fields, we
  have one of the following situations


=== FUNC/GRAD REQUEST ===
State.NeedFG is True => function value/gradient are needed.
Caller should calculate function value State.F and gradient
State.G[0..N-1] at State.X[0..N-1] and call MinLBFGSIteration() again.

=== NEW INTERATION IS REPORTED ===
State.XUpdated is True => one more iteration was made.
State.X contains current position, State.F contains function value at X.
You can read info from these fields, but never modify  them  because  they
contain the only copy of optimization algorithm state.

One and only one of these fields (NeedFG, XUpdated) is true on return. New
iterations are reported only when reports  are  explicitly  turned  on  by
MinLBFGSSetXRep() function, so if you never called it, you can expect that
NeedFG is always True.


  -- ALGLIB --
     Copyright 20.03.2009 by Bochkanov Sergey
*************************************************************************/
bool minasaiteration(minasastate& state)
{
    bool result;
    int n;
    int i;
    double betak;
    double v;
    double vv;
    int mcinfo;
    bool b;
    bool stepfound;
    int diffcnt;

    
    //
    // Reverse communication preparations
    // I know it looks ugly, but it works the same way
    // anywhere from C++ to Python.
    //
    // This code initializes locals by:
    // * random values determined during code
    //   generation - on first subroutine call
    // * values from previous call - on subsequent calls
    //
    if( state.rstate.stage>=0 )
    {
        n = state.rstate.ia(0);
        i = state.rstate.ia(1);
        mcinfo = state.rstate.ia(2);
        diffcnt = state.rstate.ia(3);
        b = state.rstate.ba(0);
        stepfound = state.rstate.ba(1);
        betak = state.rstate.ra(0);
        v = state.rstate.ra(1);
        vv = state.rstate.ra(2);
    }
    else
    {
        n = -983;
        i = -989;
        mcinfo = -834;
        diffcnt = 900;
        b = true;
        stepfound = false;
        betak = 214;
        v = -338;
        vv = -686;
    }
    if( state.rstate.stage==0 )
    {
        goto lbl_0;
    }
    if( state.rstate.stage==1 )
    {
        goto lbl_1;
    }
    if( state.rstate.stage==2 )
    {
        goto lbl_2;
    }
    if( state.rstate.stage==3 )
    {
        goto lbl_3;
    }
    if( state.rstate.stage==4 )
    {
        goto lbl_4;
    }
    if( state.rstate.stage==5 )
    {
        goto lbl_5;
    }
    if( state.rstate.stage==6 )
    {
        goto lbl_6;
    }
    if( state.rstate.stage==7 )
    {
        goto lbl_7;
    }
    if( state.rstate.stage==8 )
    {
        goto lbl_8;
    }
    if( state.rstate.stage==9 )
    {
        goto lbl_9;
    }
    if( state.rstate.stage==10 )
    {
        goto lbl_10;
    }
    if( state.rstate.stage==11 )
    {
        goto lbl_11;
    }
    if( state.rstate.stage==12 )
    {
        goto lbl_12;
    }
    if( state.rstate.stage==13 )
    {
        goto lbl_13;
    }
    if( state.rstate.stage==14 )
    {
        goto lbl_14;
    }
    
    //
    // Routine body
    //
    
    //
    // Prepare
    //
    n = state.n;
    state.repterminationtype = 0;
    state.repiterationscount = 0;
    state.repnfev = 0;
    state.debugrestartscount = 0;
    state.cgtype = 1;
    ap::vmove(&state.xk(0), 1, &state.x(0), 1, ap::vlen(0,n-1));
    for(i = 0; i <= n-1; i++)
    {
        if( ap::fp_eq(state.xk(i),state.bndl(i))||ap::fp_eq(state.xk(i),state.bndu(i)) )
        {
            state.ak(i) = 0;
        }
        else
        {
            state.ak(i) = 1;
        }
    }
    state.mu = 0.1;
    state.curalgo = 0;
    
    //
    // Calculate F/G, initialize algorithm
    //
    clearrequestfields(state);
    state.needfg = true;
    state.rstate.stage = 0;
    goto lbl_rcomm;
lbl_0:
    if( !state.xrep )
    {
        goto lbl_15;
    }
    
    //
    // progress report
    //
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 1;
    goto lbl_rcomm;
lbl_1:
lbl_15:
    if( ap::fp_less_eq(asaboundedantigradnorm(state),state.epsg) )
    {
        state.repterminationtype = 4;
        result = false;
        return result;
    }
    state.repnfev = state.repnfev+1;
    
    //
    // Main cycle
    //
    // At the beginning of new iteration:
    // * CurAlgo stores current algorithm selector
    // * State.XK, State.F and State.G store current X/F/G
    // * State.AK stores current set of active constraints
    //
lbl_17:
    if( false )
    {
        goto lbl_18;
    }
    
    //
    // GPA algorithm
    //
    if( state.curalgo!=0 )
    {
        goto lbl_19;
    }
    state.k = 0;
    state.acount = 0;
lbl_21:
    if( false )
    {
        goto lbl_22;
    }
    
    //
    // Determine Dk = proj(xk - gk)-xk
    //
    for(i = 0; i <= n-1; i++)
    {
        state.d(i) = asaboundval(state.xk(i)-state.g(i), state.bndl(i), state.bndu(i))-state.xk(i);
    }
    
    //
    // Armijo line search.
    // * exact search with alpha=1 is tried first,
    //   'exact' means that we evaluate f() EXACTLY at
    //   bound(x-g,bndl,bndu), without intermediate floating
    //   point operations.
    // * alpha<1 are tried if explicit search wasn't successful
    // Result is placed into XN.
    //
    // Two types of search are needed because we can't
    // just use second type with alpha=1 because in finite
    // precision arithmetics (x1-x0)+x0 may differ from x1.
    // So while x1 is correctly bounded (it lie EXACTLY on
    // boundary, if it is active), (x1-x0)+x0 may be
    // not bounded.
    //
    v = ap::vdotproduct(&state.d(0), 1, &state.g(0), 1, ap::vlen(0,n-1));
    state.dginit = v;
    state.finit = state.f;
    if( !(ap::fp_less_eq(asad1norm(state),state.stpmax)||ap::fp_eq(state.stpmax,0)) )
    {
        goto lbl_23;
    }
    
    //
    // Try alpha=1 step first
    //
    for(i = 0; i <= n-1; i++)
    {
        state.x(i) = asaboundval(state.xk(i)-state.g(i), state.bndl(i), state.bndu(i));
    }
    clearrequestfields(state);
    state.needfg = true;
    state.rstate.stage = 2;
    goto lbl_rcomm;
lbl_2:
    state.repnfev = state.repnfev+1;
    stepfound = ap::fp_less_eq(state.f,state.finit+gpaftol*state.dginit);
    goto lbl_24;
lbl_23:
    stepfound = false;
lbl_24:
    if( !stepfound )
    {
        goto lbl_25;
    }
    
    //
    // we are at the boundary(ies)
    //
    ap::vmove(&state.xn(0), 1, &state.x(0), 1, ap::vlen(0,n-1));
    state.stp = 1;
    goto lbl_26;
lbl_25:
    
    //
    // alpha=1 is too large, try smaller values
    //
    state.stp = 1;
    linminnormalized(state.d, state.stp, n);
    state.dginit = state.dginit/state.stp;
    state.stp = gpadecay*state.stp;
    if( ap::fp_greater(state.stpmax,0) )
    {
        state.stp = ap::minreal(state.stp, state.stpmax);
    }
lbl_27:
    if( false )
    {
        goto lbl_28;
    }
    v = state.stp;
    ap::vmove(&state.x(0), 1, &state.xk(0), 1, ap::vlen(0,n-1));
    ap::vadd(&state.x(0), 1, &state.d(0), 1, ap::vlen(0,n-1), v);
    clearrequestfields(state);
    state.needfg = true;
    state.rstate.stage = 3;
    goto lbl_rcomm;
lbl_3:
    state.repnfev = state.repnfev+1;
    if( ap::fp_less_eq(state.stp,stpmin) )
    {
        goto lbl_28;
    }
    if( ap::fp_less_eq(state.f,state.finit+state.stp*gpaftol*state.dginit) )
    {
        goto lbl_28;
    }
    state.stp = state.stp*gpadecay;
    goto lbl_27;
lbl_28:
    ap::vmove(&state.xn(0), 1, &state.x(0), 1, ap::vlen(0,n-1));
lbl_26:
    state.repiterationscount = state.repiterationscount+1;
    if( !state.xrep )
    {
        goto lbl_29;
    }
    
    //
    // progress report
    //
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 4;
    goto lbl_rcomm;
lbl_4:
lbl_29:
    
    //
    // Calculate new set of active constraints.
    // Reset counter if active set was changed.
    // Prepare for the new iteration
    //
    for(i = 0; i <= n-1; i++)
    {
        if( ap::fp_eq(state.xn(i),state.bndl(i))||ap::fp_eq(state.xn(i),state.bndu(i)) )
        {
            state.an(i) = 0;
        }
        else
        {
            state.an(i) = 1;
        }
    }
    for(i = 0; i <= n-1; i++)
    {
        if( ap::fp_neq(state.ak(i),state.an(i)) )
        {
            state.acount = -1;
            break;
        }
    }
    state.acount = state.acount+1;
    ap::vmove(&state.xk(0), 1, &state.xn(0), 1, ap::vlen(0,n-1));
    ap::vmove(&state.ak(0), 1, &state.an(0), 1, ap::vlen(0,n-1));
    
    //
    // Stopping conditions
    //
    if( !(state.repiterationscount>=state.maxits&&state.maxits>0) )
    {
        goto lbl_31;
    }
    
    //
    // Too many iterations
    //
    state.repterminationtype = 5;
    if( !state.xrep )
    {
        goto lbl_33;
    }
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 5;
    goto lbl_rcomm;
lbl_5:
lbl_33:
    result = false;
    return result;
lbl_31:
    if( ap::fp_greater(asaboundedantigradnorm(state),state.epsg) )
    {
        goto lbl_35;
    }
    
    //
    // Gradient is small enough
    //
    state.repterminationtype = 4;
    if( !state.xrep )
    {
        goto lbl_37;
    }
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 6;
    goto lbl_rcomm;
lbl_6:
lbl_37:
    result = false;
    return result;
lbl_35:
    v = ap::vdotproduct(&state.d(0), 1, &state.d(0), 1, ap::vlen(0,n-1));
    if( ap::fp_greater(sqrt(v)*state.stp,state.epsx) )
    {
        goto lbl_39;
    }
    
    //
    // Step size is too small, no further improvement is
    // possible
    //
    state.repterminationtype = 2;
    if( !state.xrep )
    {
        goto lbl_41;
    }
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 7;
    goto lbl_rcomm;
lbl_7:
lbl_41:
    result = false;
    return result;
lbl_39:
    if( ap::fp_greater(state.finit-state.f,state.epsf*ap::maxreal(fabs(state.finit), ap::maxreal(fabs(state.f), 1.0))) )
    {
        goto lbl_43;
    }
    
    //
    // F(k+1)-F(k) is small enough
    //
    state.repterminationtype = 1;
    if( !state.xrep )
    {
        goto lbl_45;
    }
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 8;
    goto lbl_rcomm;
lbl_8:
lbl_45:
    result = false;
    return result;
lbl_43:
    
    //
    // Decide - should we switch algorithm or not
    //
    if( asauisempty(state) )
    {
        if( ap::fp_greater_eq(asaginorm(state),state.mu*asad1norm(state)) )
        {
            state.curalgo = 1;
            goto lbl_22;
        }
        else
        {
            state.mu = state.mu*asarho;
        }
    }
    else
    {
        if( state.acount==n1 )
        {
            if( ap::fp_greater_eq(asaginorm(state),state.mu*asad1norm(state)) )
            {
                state.curalgo = 1;
                goto lbl_22;
            }
        }
    }
    
    //
    // Next iteration
    //
    state.k = state.k+1;
    goto lbl_21;
lbl_22:
lbl_19:
    
    //
    // CG algorithm
    //
    if( state.curalgo!=1 )
    {
        goto lbl_47;
    }
    
    //
    // first, check that there are non-active constraints.
    // move to GPA algorithm, if all constraints are active
    //
    b = true;
    for(i = 0; i <= n-1; i++)
    {
        if( ap::fp_neq(state.ak(i),0) )
        {
            b = false;
            break;
        }
    }
    if( b )
    {
        state.curalgo = 0;
        goto lbl_17;
    }
    
    //
    // CG iterations
    //
    state.fold = state.f;
    ap::vmove(&state.xk(0), 1, &state.x(0), 1, ap::vlen(0,n-1));
    for(i = 0; i <= n-1; i++)
    {
        state.dk(i) = -state.g(i)*state.ak(i);
        state.gc(i) = state.g(i)*state.ak(i);
    }
lbl_49:
    if( false )
    {
        goto lbl_50;
    }
    
    //
    // Store G[k] for later calculation of Y[k]
    //
    for(i = 0; i <= n-1; i++)
    {
        state.yk(i) = -state.gc(i);
    }
    
    //
    // Make a CG step in direction given by DK[]:
    // * calculate step. Step projection into feasible set
    //   is used. It has several benefits: a) step may be
    //   found with usual line search, b) multiple constraints
    //   may be activated with one step, c) activated constraints
    //   are detected in a natural way - just compare x[i] with
    //   bounds
    // * update active set, set B to True, if there
    //   were changes in the set.
    //
    ap::vmove(&state.d(0), 1, &state.dk(0), 1, ap::vlen(0,n-1));
    ap::vmove(&state.xn(0), 1, &state.xk(0), 1, ap::vlen(0,n-1));
    state.mcstage = 0;
    state.stp = 1;
    linminnormalized(state.d, state.stp, n);
    mcsrch(n, state.xn, state.f, state.gc, state.d, state.stp, state.stpmax, mcinfo, state.nfev, state.work, state.lstate, state.mcstage);
lbl_51:
    if( state.mcstage==0 )
    {
        goto lbl_52;
    }
    
    //
    // preprocess data: bound State.XN so it belongs to the
    // feasible set and store it in the State.X
    //
    for(i = 0; i <= n-1; i++)
    {
        state.x(i) = asaboundval(state.xn(i), state.bndl(i), state.bndu(i));
    }
    
    //
    // RComm
    //
    clearrequestfields(state);
    state.needfg = true;
    state.rstate.stage = 9;
    goto lbl_rcomm;
lbl_9:
    
    //
    // postprocess data: zero components of G corresponding to
    // the active constraints
    //
    for(i = 0; i <= n-1; i++)
    {
        if( ap::fp_eq(state.x(i),state.bndl(i))||ap::fp_eq(state.x(i),state.bndu(i)) )
        {
            state.gc(i) = 0;
        }
        else
        {
            state.gc(i) = state.g(i);
        }
    }
    mcsrch(n, state.xn, state.f, state.gc, state.d, state.stp, state.stpmax, mcinfo, state.nfev, state.work, state.lstate, state.mcstage);
    goto lbl_51;
lbl_52:
    diffcnt = 0;
    for(i = 0; i <= n-1; i++)
    {
        
        //
        // XN contains unprojected result, project it,
        // save copy to X (will be used for progress reporting)
        //
        state.xn(i) = asaboundval(state.xn(i), state.bndl(i), state.bndu(i));
        
        //
        // update active set
        //
        if( ap::fp_eq(state.xn(i),state.bndl(i))||ap::fp_eq(state.xn(i),state.bndu(i)) )
        {
            state.an(i) = 0;
        }
        else
        {
            state.an(i) = 1;
        }
        if( ap::fp_neq(state.an(i),state.ak(i)) )
        {
            diffcnt = diffcnt+1;
        }
        state.ak(i) = state.an(i);
    }
    ap::vmove(&state.xk(0), 1, &state.xn(0), 1, ap::vlen(0,n-1));
    state.repnfev = state.repnfev+state.nfev;
    state.repiterationscount = state.repiterationscount+1;
    if( !state.xrep )
    {
        goto lbl_53;
    }
    
    //
    // progress report
    //
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 10;
    goto lbl_rcomm;
lbl_10:
lbl_53:
    
    //
    // Check stopping conditions.
    //
    if( ap::fp_greater(asaboundedantigradnorm(state),state.epsg) )
    {
        goto lbl_55;
    }
    
    //
    // Gradient is small enough
    //
    state.repterminationtype = 4;
    if( !state.xrep )
    {
        goto lbl_57;
    }
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 11;
    goto lbl_rcomm;
lbl_11:
lbl_57:
    result = false;
    return result;
lbl_55:
    if( !(state.repiterationscount>=state.maxits&&state.maxits>0) )
    {
        goto lbl_59;
    }
    
    //
    // Too many iterations
    //
    state.repterminationtype = 5;
    if( !state.xrep )
    {
        goto lbl_61;
    }
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 12;
    goto lbl_rcomm;
lbl_12:
lbl_61:
    result = false;
    return result;
lbl_59:
    if( !(ap::fp_greater_eq(asaginorm(state),state.mu*asad1norm(state))&&diffcnt==0) )
    {
        goto lbl_63;
    }
    
    //
    // These conditions are explicitly or implicitly
    // related to the current step size and influenced
    // by changes in the active constraints.
    //
    // For these reasons they are checked only when we don't
    // want to 'unstick' at the end of the iteration and there
    // were no changes in the active set.
    //
    // NOTE: consition |G|>=Mu*|D1| must be exactly opposite
    // to the condition used to switch back to GPA. At least
    // one inequality must be strict, otherwise infinite cycle
    // may occur when |G|=Mu*|D1| (we DON'T test stopping
    // conditions and we DON'T switch to GPA, so we cycle
    // indefinitely).
    //
    if( ap::fp_greater(state.fold-state.f,state.epsf*ap::maxreal(fabs(state.fold), ap::maxreal(fabs(state.f), 1.0))) )
    {
        goto lbl_65;
    }
    
    //
    // F(k+1)-F(k) is small enough
    //
    state.repterminationtype = 1;
    if( !state.xrep )
    {
        goto lbl_67;
    }
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 13;
    goto lbl_rcomm;
lbl_13:
lbl_67:
    result = false;
    return result;
lbl_65:
    v = ap::vdotproduct(&state.d(0), 1, &state.d(0), 1, ap::vlen(0,n-1));
    if( ap::fp_greater(sqrt(v)*state.stp,state.epsx) )
    {
        goto lbl_69;
    }
    
    //
    // X(k+1)-X(k) is small enough
    //
    state.repterminationtype = 2;
    if( !state.xrep )
    {
        goto lbl_71;
    }
    clearrequestfields(state);
    state.xupdated = true;
    state.rstate.stage = 14;
    goto lbl_rcomm;
lbl_14:
lbl_71:
    result = false;
    return result;
lbl_69:
lbl_63:
    
    //
    // Check conditions for switching
    //
    if( ap::fp_less(asaginorm(state),state.mu*asad1norm(state)) )
    {
        state.curalgo = 0;
        goto lbl_50;
    }
    if( diffcnt>0 )
    {
        if( asauisempty(state)||diffcnt>=n2 )
        {
            state.curalgo = 1;
        }
        else
        {
            state.curalgo = 0;
        }
        goto lbl_50;
    }
    
    //
    // Calculate D(k+1)
    //
    // Line search may result in:
    // * maximum feasible step being taken (already processed)
    // * point satisfying Wolfe conditions
    // * some kind of error (CG is restarted by assigning 0.0 to Beta)
    //
    if( mcinfo==1 )
    {
        
        //
        // Standard Wolfe conditions are satisfied:
        // * calculate Y[K] and BetaK
        //
        ap::vadd(&state.yk(0), 1, &state.gc(0), 1, ap::vlen(0,n-1));
        vv = ap::vdotproduct(&state.yk(0), 1, &state.dk(0), 1, ap::vlen(0,n-1));
        v = ap::vdotproduct(&state.gc(0), 1, &state.gc(0), 1, ap::vlen(0,n-1));
        state.betady = v/vv;
        v = ap::vdotproduct(&state.gc(0), 1, &state.yk(0), 1, ap::vlen(0,n-1));
        state.betahs = v/vv;
        if( state.cgtype==0 )
        {
            betak = state.betady;
        }
        if( state.cgtype==1 )
        {
            betak = ap::maxreal(double(0), ap::minreal(state.betady, state.betahs));
        }
    }
    else
    {
        
        //
        // Something is wrong (may be function is too wild or too flat).
        //
        // We'll set BetaK=0, which will restart CG algorithm.
        // We can stop later (during normal checks) if stopping conditions are met.
        //
        betak = 0;
        state.debugrestartscount = state.debugrestartscount+1;
    }
    ap::vmoveneg(&state.dn(0), 1, &state.gc(0), 1, ap::vlen(0,n-1));
    ap::vadd(&state.dn(0), 1, &state.dk(0), 1, ap::vlen(0,n-1), betak);
    ap::vmove(&state.dk(0), 1, &state.dn(0), 1, ap::vlen(0,n-1));
    
    //
    // update other information
    //
    state.fold = state.f;
    state.k = state.k+1;
    goto lbl_49;
lbl_50:
lbl_47:
    goto lbl_17;
lbl_18:
    result = false;
    return result;
    
    //
    // Saving state
    //
lbl_rcomm:
    result = true;
    state.rstate.ia(0) = n;
    state.rstate.ia(1) = i;
    state.rstate.ia(2) = mcinfo;
    state.rstate.ia(3) = diffcnt;
    state.rstate.ba(0) = b;
    state.rstate.ba(1) = stepfound;
    state.rstate.ra(0) = betak;
    state.rstate.ra(1) = v;
    state.rstate.ra(2) = vv;
    return result;
}
int test_main(int,char *[])
{
    // default constructor
    const bu::quantity<bu::dimensionless>           E1; 
    BOOST_CHECK(E1.value() == double());
    
    // value_type constructor
    const bu::quantity<bu::dimensionless>           E2(E_);
    BOOST_CHECK(E2.value() == E_);

    // copy constructor
    const bu::quantity<bu::dimensionless>           E3(E2);
    BOOST_CHECK(E3.value() == E_);

    // operator=
    const bu::quantity<bu::dimensionless>           E4 = E2;
    BOOST_CHECK(E4.value() == E_);

    // implicit copy constructor value_type conversion
    const bu::quantity<bu::dimensionless,float>     E5(E2);
    BOOST_UNITS_CHECK_CLOSE(E5.value(), float(E_));

    const bu::quantity<bu::dimensionless,long>      E6(E2);
    BOOST_CHECK(E6.value() == long(E_));

    // implicit operator= value_type conversion
    // narrowing conversion disallowed
//    const bu::quantity<bu::dimensionless,float>     E7 = E2;
//    BOOST_UNITS_CHECK_CLOSE(E7.value(),float(E_));
    
    // narrowing conversion disallowed
//    const bu::quantity<bu::dimensionless,long>      E8 = E2;
//    BOOST_CHECK(E8.value() == long(E_));
    
    // const construction
    bu::quantity<bu::dimensionless>                 E9(E2); 
    BOOST_CHECK(E9.value() == E_);
    
//    // value assignment
//    E9.value() = 1.5*bu::dimensionless();
//    BOOST_CHECK(E9.value() == 1.5);
//    
//    // value assignment with implicit conversion
//    E9.value() = 1.5;
//    BOOST_CHECK(E9.value() == 1.5);
//    
//    // value assignment with implicit value_type conversion
//    E9.value() = 2*bu::dimensionless();
//    BOOST_CHECK(E9.value() == double(2));
//
//    // value assignment with implicit value_type conversion
//    E9.value() = 2;
//    BOOST_CHECK(E9.value() == double(2));
    
    // operator+=(this_type)
    E9 = 2.0;
    E9 += E9;
    BOOST_CHECK(E9.value() == 4.0);
    
    // operator-=(this_type)
    E9 = 2.0;
    E9 -= E9;
    BOOST_CHECK(E9.value() == 0.0);
    
    // operator*=(value_type)
    E9 = 2.0;
    E9 *= 2.0;
    BOOST_CHECK(E9.value() == 4.0);
    
    // operator/=(value_type)
    E9 = 2.0;
    E9 /= 2.0;
    BOOST_CHECK(E9.value() == 1.0);
    
    // static construct quantity from value_type
    const bu::quantity<bu::dimensionless>           E(bu::quantity<bu::dimensionless>::from_value(2.5));
    BOOST_CHECK(E.value() == 2.5);
    
    // implicit conversion to value_type
    const double    V1(E9);
    BOOST_CHECK(V1 == E9.value());
    
    const double    V2 = E9;
    BOOST_CHECK(V2 == E9.value());
            
    // unit * scalar
    BOOST_CHECK(bu::dimensionless()*2.0 == bu::quantity<bu::dimensionless>::from_value(2.0));
    
    // unit / scalar
    BOOST_CHECK(bu::dimensionless()/2.0 == bu::quantity<bu::dimensionless>::from_value(0.5));
    
    // scalar * unit
    BOOST_CHECK(2.0*bu::dimensionless() == bu::quantity<bu::dimensionless>::from_value(2.0));
    
    // scalar / unit
    BOOST_CHECK(2.0/bu::dimensionless() == bu::quantity<bu::dimensionless>::from_value(2.0));

    //  quantity * scalar
    BOOST_CHECK(E*2.0 == bu::quantity<bu::dimensionless>::from_value(5.0));

    //  quantity / scalar
    BOOST_CHECK(E/2.0 == bu::quantity<bu::dimensionless>::from_value(1.25));
    
    // scalar * quantity
    BOOST_CHECK(2.0*E == bu::quantity<bu::dimensionless>::from_value(5.0));

    // scalar / quantity
    BOOST_CHECK(2.0/E == bu::quantity<bu::dimensionless>::from_value(0.8));

    const bu::quantity<bu::dimensionless>       D1(1.0),
                                                D2(2.0);
    
    // unit * quantity
    BOOST_CHECK(bu::dimensionless()*D1 == D1);
    
    // unit / quantity
    BOOST_CHECK(bu::dimensionless()/D1 == D1);
    
    // quantity * unit
    BOOST_CHECK(D1*bu::dimensionless() == D1);
    
    // quantity / unit
    BOOST_CHECK(D1*bu::dimensionless() == D1);
    
    // +quantity
    BOOST_CHECK(+D1 == 1.0*bu::dimensionless());
    
    // -quantity
    BOOST_CHECK(-D1 == -1.0*bu::dimensionless());
    
    // quantity + quantity
    BOOST_CHECK(D2+D1 == 3.0*bu::dimensionless());
    
    // quantity - quantity
    BOOST_CHECK(D2-D1 == 1.0*bu::dimensionless());
    
    // quantity * quantity
    BOOST_CHECK(D1*D2 == 2.0*bu::dimensionless());
    
    // quantity / quantity
    BOOST_CHECK(D2/D1 == 2.0*bu::dimensionless());
    
    // integer power of quantity
    BOOST_CHECK(2.0*bu::pow<2>(D2) == 2.0*std::pow(2.0,2.0)*bu::dimensionless());
    
    // rational power of quantity
    BOOST_CHECK((2.0*bu::pow< bu::static_rational<2,3> >(D2) == 2.0*std::pow(2.0,2.0/3.0)*bu::dimensionless()));
    
    // integer root of quantity
    BOOST_CHECK(2.0*bu::root<2>(D2) == 2.0*std::pow(2.0,1.0/2.0)*bu::dimensionless());
    
    // rational root of quantity
    BOOST_CHECK((2.0*bu::root< bu::static_rational<3,2> >(D2) == 2.0*std::pow(2.0,2.0/3.0)*bu::dimensionless()));
    
    const bu::quantity<bu::dimensionless>   A1(0.0),
                                            A2(0.0),
                                            A3(1.0),
                                            A4(-1.0);
                                    
    // operator==
    BOOST_CHECK((A1 == A2) == true);
    BOOST_CHECK((A1 == A3) == false);
    
    // operator!=
    BOOST_CHECK((A1 != A2) == false);
    BOOST_CHECK((A1 != A3) == true);
    
    // operator<
    BOOST_CHECK((A1 < A2) == false);
    BOOST_CHECK((A1 < A3) == true);
    
    // operator<=
    BOOST_CHECK((A1 <= A2) == true);
    BOOST_CHECK((A1 <= A3) == true);
    
    // operator>
    BOOST_CHECK((A1 > A2) == false);
    BOOST_CHECK((A1 > A4) == true);
    
    // operator>=
    BOOST_CHECK((A1 >= A2) == true);
    BOOST_CHECK((A1 >= A4) == true);
    
    return 0;
}
Beispiel #5
0
int _main_(int /*_argc*/, char** /*_argv*/)
{
	uint32_t width = 1280;
	uint32_t height = 720;
	uint32_t debug = BGFX_DEBUG_TEXT;
	uint32_t reset = BGFX_RESET_VSYNC;

	bgfx::init();
	bgfx::reset(width, height, reset);

	// Enable debug text.
	bgfx::setDebug(debug);

	// Set view 0 clear state.
	bgfx::setViewClear(0
		, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
		, 0x303030ff
		, 1.0f
		, 0
		);

	// Get renderer capabilities info.
	const bgfx::Caps* caps = bgfx::getCaps();
	bool instancingSupported = 0 != (caps->supported & BGFX_CAPS_INSTANCING);

	// Create vertex stream declaration.
	PosNormalTangentTexcoordVertex::init();

	calcTangents(s_cubeVertices
		, BX_COUNTOF(s_cubeVertices)
		, PosNormalTangentTexcoordVertex::ms_decl
		, s_cubeIndices
		, BX_COUNTOF(s_cubeIndices)
		);

	// Create static vertex buffer.
	bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(
		  bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
		, PosNormalTangentTexcoordVertex::ms_decl
		);

	// Create static index buffer.
	bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) );

	// Create texture sampler uniforms.
	bgfx::UniformHandle u_texColor  = bgfx::createUniform("u_texColor",  bgfx::UniformType::Int1);
	bgfx::UniformHandle u_texNormal = bgfx::createUniform("u_texNormal", bgfx::UniformType::Int1);

	uint16_t numLights = 4;
	bgfx::UniformHandle u_lightPosRadius = bgfx::createUniform("u_lightPosRadius", bgfx::UniformType::Vec4, numLights);
	bgfx::UniformHandle u_lightRgbInnerR = bgfx::createUniform("u_lightRgbInnerR", bgfx::UniformType::Vec4, numLights);

	// Create program from shaders.
	bgfx::ProgramHandle program = loadProgram(instancingSupported ? "vs_bump_instanced" : "vs_bump", "fs_bump");

	// Load diffuse texture.
	bgfx::TextureHandle textureColor = loadTexture("fieldstone-rgba.dds");

	// Load normal texture.
	bgfx::TextureHandle textureNormal = loadTexture("fieldstone-n.dds");

	int64_t timeOffset = bx::getHPCounter();

	while (!entry::processEvents(width, height, debug, reset) )
	{
		// Set view 0 default viewport.
		bgfx::setViewRect(0, 0, 0, width, height);

		// This dummy draw call is here to make sure that view 0 is cleared
		// if no other draw calls are submitted to view 0.
		bgfx::submit(0);

		int64_t now = bx::getHPCounter();
		static int64_t last = now;
		const int64_t frameTime = now - last;
		last = now;
		const double freq = double(bx::getHPFrequency() );
		const double toMs = 1000.0/freq;

		float time = (float)( (now-timeOffset)/freq);

		// Use debug font to print information about this example.
		bgfx::dbgTextClear();
		bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/06-bump");
		bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Loading textures.");
		bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);

		float at[3]  = { 0.0f, 0.0f,  0.0f };
		float eye[3] = { 0.0f, 0.0f, -7.0f };

		// Set view and projection matrix for view 0.
		const bgfx::HMD* hmd = bgfx::getHMD();
		if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING))
		{
			float view[16];
			bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye);

			float proj[16];
			bx::mtxProj(proj, hmd->eye[0].fov, 0.1f, 100.0f);

			bgfx::setViewTransform(0, view, proj);

			// Set view 0 default viewport.
			//
			// Use HMD's width/height since HMD's internal frame buffer size
			// might be much larger than window size.
			bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height);
		}
		else
		{
			float view[16];
			bx::mtxLookAt(view, eye, at);

			float proj[16];
			bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f);
			bgfx::setViewTransform(0, view, proj);

			// Set view 0 default viewport.
			bgfx::setViewRect(0, 0, 0, width, height);
		}

		float lightPosRadius[4][4];
		for (uint32_t ii = 0; ii < numLights; ++ii)
		{
			lightPosRadius[ii][0] = sinf( (time*(0.1f + ii*0.17f) + ii*bx::piHalf*1.37f ) )*3.0f;
			lightPosRadius[ii][1] = cosf( (time*(0.2f + ii*0.29f) + ii*bx::piHalf*1.49f ) )*3.0f;
			lightPosRadius[ii][2] = -2.5f;
			lightPosRadius[ii][3] = 3.0f;
		}

		bgfx::setUniform(u_lightPosRadius, lightPosRadius, numLights);

		float lightRgbInnerR[4][4] =
		{
			{ 1.0f, 0.7f, 0.2f, 0.8f },
			{ 0.7f, 0.2f, 1.0f, 0.8f },
			{ 0.2f, 1.0f, 0.7f, 0.8f },
			{ 1.0f, 0.4f, 0.2f, 0.8f },
		};

		bgfx::setUniform(u_lightRgbInnerR, lightRgbInnerR, numLights);

		const uint16_t instanceStride = 64;
		const uint16_t numInstances = 3;

		if (instancingSupported)
		{
			// Write instance data for 3x3 cubes.
			for (uint32_t yy = 0; yy < 3; ++yy)
			{
				const bgfx::InstanceDataBuffer* idb = bgfx::allocInstanceDataBuffer(numInstances, instanceStride);
				if (NULL != idb)
				{
					uint8_t* data = idb->data;

					for (uint32_t xx = 0; xx < 3; ++xx)
					{
						float* mtx = (float*)data;
						bx::mtxRotateXY(mtx, time*0.023f + xx*0.21f, time*0.03f + yy*0.37f);
						mtx[12] = -3.0f + float(xx)*3.0f;
						mtx[13] = -3.0f + float(yy)*3.0f;
						mtx[14] = 0.0f;

						data += instanceStride;
					}

					// Set instance data buffer.
					bgfx::setInstanceDataBuffer(idb, numInstances);

					// Set vertex and fragment shaders.
					bgfx::setProgram(program);

					// Set vertex and index buffer.
					bgfx::setVertexBuffer(vbh);
					bgfx::setIndexBuffer(ibh);

					// Bind textures.
					bgfx::setTexture(0, u_texColor, textureColor);
					bgfx::setTexture(1, u_texNormal, textureNormal);

					// Set render states.
					bgfx::setState(0
						| BGFX_STATE_RGB_WRITE
						| BGFX_STATE_ALPHA_WRITE
						| BGFX_STATE_DEPTH_WRITE
						| BGFX_STATE_DEPTH_TEST_LESS
						| BGFX_STATE_MSAA
						);

					// Submit primitive for rendering to view 0.
					bgfx::submit(0);
				}
			}
		}
		else
		{
			for (uint32_t yy = 0; yy < 3; ++yy)
			{
				for (uint32_t xx = 0; xx < 3; ++xx)
				{
					float mtx[16];
					bx::mtxRotateXY(mtx, time*0.023f + xx*0.21f, time*0.03f + yy*0.37f);
					mtx[12] = -3.0f + float(xx)*3.0f;
					mtx[13] = -3.0f + float(yy)*3.0f;
					mtx[14] = 0.0f;

					// Set transform for draw call.
					bgfx::setTransform(mtx);

					// Set vertex and fragment shaders.
					bgfx::setProgram(program);

					// Set vertex and index buffer.
					bgfx::setVertexBuffer(vbh);
					bgfx::setIndexBuffer(ibh);

					// Bind textures.
					bgfx::setTexture(0, u_texColor, textureColor);
					bgfx::setTexture(1, u_texNormal, textureNormal);

					// Set render states.
					bgfx::setState(0
						| BGFX_STATE_RGB_WRITE
						| BGFX_STATE_ALPHA_WRITE
						| BGFX_STATE_DEPTH_WRITE
						| BGFX_STATE_DEPTH_TEST_LESS
						| BGFX_STATE_MSAA
						);

					// Submit primitive for rendering to view 0.
					bgfx::submit(0);
				}
			}
		}

		// Advance to next frame. Rendering thread will be kicked to
		// process submitted rendering primitives.
		bgfx::frame();
	}

	// Cleanup.
	bgfx::destroyIndexBuffer(ibh);
	bgfx::destroyVertexBuffer(vbh);
	bgfx::destroyProgram(program);
	bgfx::destroyTexture(textureColor);
	bgfx::destroyTexture(textureNormal);
	bgfx::destroyUniform(u_texColor);
	bgfx::destroyUniform(u_texNormal);
	bgfx::destroyUniform(u_lightPosRadius);
	bgfx::destroyUniform(u_lightRgbInnerR);

	// Shutdown bgfx.
	bgfx::shutdown();

	return 0;
}
/**
 * Generates the value of pi as a function of
 * the number of random points generated and
 * the number of those points which were in a
 * circle
 */
double generatePi(int hits, int tries) {
  return 4 * double(hits) / double(tries);
}
Beispiel #7
0
int __cdecl _fpclassl (long double x) {
   return _fpclass(double(x));
}
void cCustomers::GenerateCustomers(sBrothel * brothel, bool Day0Night1)
{
	Free();	// Free any existing customers
	if (brothel->m_NumGirls == 0) return;	// no girls, no customers

	stringstream ss;
	string daynighttime = (Day0Night1 ? gettext("nighttime") : gettext("daytime"));
	/*
 *	base number of customers = number of girls times 1.5f
 *	(was set to time 5 - reverting it to agree with the comment for now
 *	--doc)
 *
 *	adding a .5 bonus to night time trade as well - should see more 
 *	punters after dark it seems to me
 */
	m_NumCustomers = int(brothel->m_NumGirls * (Day0Night1 ? 2.0 : 1.5));
	ss << gettext("The number of girls in this brothel attracted ") << m_NumCustomers << gettext(" initial ") << daynighttime << gettext(" customers.\n\n");
/*
 *	the customers attracted by the places fame (for this shift)
 *	is the fame divided by 4 (so a max of 25 people)
 *	they may be culled by randomizing this value
 *	(halved the number -- doc)
 */
	int fame_customers = brothel->m_Fame / 4;
	ss << gettext("This brothel's fame enticed ") << fame_customers << gettext(" additional ") << daynighttime << gettext(" customers to visit.\n\n");
	m_NumCustomers += fame_customers;

	// each 100 gold of advertising adds 6 customers which is then randomized a little
	if (brothel->m_AdvertisingBudget > 0 || brothel->m_AdvertisingLevel > 1.0)
	{  // advertising value is actual gold budget multiplied by advertising level, set by girls working in advertising
		double advert = double(brothel->m_AdvertisingBudget);
		if (brothel->m_AdvertisingLevel > 1.0) advert += 50;	// a 50 gold gimme if you have girls working on advertising
		advert *= brothel->m_AdvertisingLevel;					// apply multiplier from girls working on advertising
		int custsFromAds = int(advert * 0.06);					// 6 customers per 100 gold or so
		custsFromAds = g_Dice%custsFromAds + (custsFromAds / 2);  // randomized from 50% to 150%
		ss << gettext("You brought in ") << custsFromAds << gettext(" more ") << daynighttime << gettext(" customers through advertising.\n\n");
		m_NumCustomers += custsFromAds;
	}

	// filthiness will take away customers
	int LostCustomers = int(brothel->m_Filthiness / 10); // was /3, but that was overly harsh; changed to /10
	m_NumCustomers -= LostCustomers;

	if(LostCustomers <= 0)
		ss << gettext("Your brothel was spotlessly clean, so you didn't lose any ") << daynighttime << gettext(" customers due to filthiness.\n\n");
	else
		ss << gettext("You lost ") << LostCustomers << " " << daynighttime << gettext(" customers due to the filthiness of your brothel.\n\n");


	// `J` Too much security will scare away customers
	int ScareCustomers = int(brothel->m_SecurityLevel / 500);	// this number will need to be tweaked a bit
	ScareCustomers -= 4;	// less security could attract more customers (for good or bad)
	if (ScareCustomers < 0) ScareCustomers = (g_Dice % 3) * -1;
	if (ScareCustomers > 10) ScareCustomers += g_Dice%ScareCustomers;
	m_NumCustomers -= ScareCustomers;

	if (ScareCustomers < 0)
	{
		ss << "Your nonintrusive security attracted " << -ScareCustomers << " " << daynighttime << " customers. (for better or worse)";
	}
	else if (ScareCustomers == 0)
		ss << gettext("Your brothel was safe and secure, so you didn't lose any ") << daynighttime << gettext(" customers due to excessive security.");
	else if (ScareCustomers < 10)
		ss << gettext("You lost ") << ScareCustomers << " " << daynighttime << gettext(" customers due to the excessive security in your brothel.");
	else
		ss << gettext("You lost ") << ScareCustomers << " " << daynighttime << gettext(" customers due to the oppressive security in your brothel.");
	brothel->m_Events.AddMessage(ss.str(), IMGTYPE_PROFILE, EVENT_BROTHEL);


	if (m_NumCustomers < 0)  // negative number of customers doesn't make sense
		m_NumCustomers = 0;
}
Beispiel #9
0
MStatus vxCacheDeformer::deform( MDataBlock& block,
				MItGeometry& iter,
				const MMatrix& m,
				unsigned int multiIndex)
{
	MStatus returnStatus;
	
	MDataHandle envData = block.inputValue(envelope,&returnStatus);
	float env = envData.asFloat();
	if(env == 0) return returnStatus;
	
	double time = block.inputValue( frame ).asTime().value();
	
	MDataHandle inPathData = block.inputValue( path );
	MString str_path =  inPathData.asString();
	
	MDataHandle inMinFrmData = block.inputValue( aminframe );
	int minfrm = inMinFrmData.asInt();
	
	MDataHandle inMaxFrmData = block.inputValue( amaxframe );
	MDataHandle inFrmStepData = block.inputValue( aframestep );
	int frmstep = inFrmStepData.asInt();
	
	if( time < minfrm )
		time = minfrm;
		
	int frame_lo = minfrm + int(time-minfrm)/frmstep*frmstep;
	int frame_hi = frame_lo+frmstep;
	
	if( strlen( str_path.asChar() ) > 0 ) 
	{
	
		char filename[256];
		sprintf( filename, "%s.%d.mcf", str_path.asChar(), frame_lo );
	
		FMCFMesh mesh;
		if(mesh.load(filename) != 1)
		{
			MGlobal::displayError( MString("Failed to open file: ") + filename );
			return MS::kFailure;
		}
		
		int lo_n_vertex = mesh.getNumVertex();
		
		vertexArray.clear();
		vertexFArray.clear();
		
		XYZ tp;
		for(unsigned int i = 0; i < mesh.getNumVertex(); i++) {
			mesh.getVertex(tp, i);
			vertexArray.append( MPoint( tp.x, tp.y, tp.z ) );
		}

		if( time > frame_lo ) 
		{
			sprintf( filename, "%s.%d.mcf", str_path.asChar(), frame_hi );

			if(mesh.load(filename) != 1) MGlobal::displayError( MString("Failed to open file: ") + filename );

			else if(mesh.getNumVertex() == lo_n_vertex)
			{
				XYZ tp;
				for(unsigned int i = 0; i < mesh.getNumVertex(); i++) 
				{
					mesh.getVertex(tp, i);
					vertexFArray.append( MPoint( tp.x, tp.y, tp.z ) );
				}
				
				double alpha = double(time-frame_lo) / (double)frmstep;

				for(unsigned int i = 0; i < mesh.getNumVertex(); i++) {
					
					vertexArray[i] = vertexArray[i] + ( vertexFArray[i] - vertexArray[i] )*alpha;
					
				}
			}
		}

		// iterate through each point in the geometry
		//
		for ( ; !iter.isDone(); iter.next()) 
		{
			MPoint pt = iter.position();
			pt = pt + (vertexArray[iter.index()] - pt)*env;
			iter.setPosition(pt);
		}
	}
	
	return returnStatus;
}
Beispiel #10
0
/*
#ifndef _ieeemisc_.obj
int __cdecl _fpclassf (float x) {
   return _fpclass(double(x));
}
#else
extern int __cdecl _fpclassf (float);
#endif
*/
int __cdecl _fpclassf (float x) {
   return _fpclass(double(x));
}
Beispiel #11
0
void CostObject::calculateCashFlows( int analysisPeriod )
{
  m_cashFlows.clear(); //clear out result
  m_cashFlows_Inflation.clear();
  m_cashFlows_Gas_Inflation.clear();
  m_cashFlows_Elec_Inflation.clear();
  m_cashFlows_DistrictHeat_Inflation.clear();
  m_cashFlows_DistrictCool_Inflation.clear();
  m_cashFlows_Capital_Inflation.clear();

  m_cashFlows.resize(analysisPeriod + 1);
  m_cashFlows_Inflation.resize(analysisPeriod + 1);
  m_cashFlows_Gas_Inflation.resize(analysisPeriod + 1);
  m_cashFlows_Elec_Inflation.resize(analysisPeriod + 1);
  m_cashFlows_DistrictHeat_Inflation.resize(analysisPeriod + 1);
  m_cashFlows_DistrictCool_Inflation.resize(analysisPeriod + 1);
  m_cashFlows_Capital_Inflation.resize(analysisPeriod + 1);

  for (int iYear = 0; iYear <= analysisPeriod; iYear++) //year 0 is initial capital
  {
    double PVIF = double( 1 ) / ( pow( 1 + m_discountRate, iYear ) );
    for (unsigned j = 0; j < m_RefCostObjsData.size(); j++)
    {
      if ( iYear == 0 ) 
      {
        m_cashFlows.at(iYear) = m_cashFlows.at(iYear) - m_RefCostObjsData.at(j)->matCost() - m_RefCostObjsData.at(j)->installCost();
        m_cashFlows_Inflation.at(iYear) = m_cashFlows_Inflation.at(iYear) - PVIF * ( ( pow( 1 + m_inflation, iYear ) * ( m_RefCostObjsData.at(j)->matCost() + m_RefCostObjsData.at(j)->installCost() ) ) );
        m_cashFlows_Capital_Inflation.at(iYear) = m_cashFlows_Inflation.at(iYear) - PVIF * ( 0 );
      }
      else
      {
        // TODO / NOTE : need to determine why there is a J==0 case.  Was this specific to the original OptEPlus code for a dummy placeholder for metadata?
        // In this application, Matt L. had only 1 costinstance and need O & M data.  He had to gen a dummy first costinstance to get valid results specific
        // to fixed O & M.
        if ( j == 0 ) 
        {
          //add energy cost
          m_cashFlows.at(iYear) = m_cashFlows.at(iYear) - m_elecCost - m_gasCost - m_districtHeatCost - m_districtCoolCost;
          m_cashFlows_Inflation.at(iYear) = m_cashFlows_Inflation.at(iYear) - PVIF * ( ( pow( 1 + m_elecInflation, iYear ) * ( m_elecCost ) ) + ( pow( 1 + m_gasInflation, iYear ) * ( m_gasCost ) ) + ( pow( 1 + m_districtHeatInflation, iYear ) * ( m_districtHeatCost ) ) + ( pow( 1 + m_districtCoolInflation, iYear ) * ( m_districtCoolCost ) ) );

          //these are used for graphing the results in the detailed results browser
          m_cashFlows_Gas_Inflation.at(iYear) = - PVIF * ( pow( 1 + m_gasInflation, iYear ) * ( m_gasCost ) );
          m_cashFlows_Elec_Inflation.at(iYear) = - PVIF * ( pow( 1 + m_elecInflation, iYear ) * ( m_elecCost ) );
          m_cashFlows_DistrictHeat_Inflation.at(iYear) = - PVIF * ( pow( 1 + m_districtHeatInflation, iYear ) * ( m_districtHeatCost ) );
          m_cashFlows_DistrictCool_Inflation.at(iYear) = - PVIF * ( pow( 1 + m_districtCoolInflation, iYear ) * ( m_districtCoolCost ) );
        }
        else
        {
          m_cashFlows.at(iYear) = m_cashFlows.at(iYear) - m_RefCostObjsData.at(j)->fixedOM() - m_RefCostObjsData.at(j)->variableOM();
          m_cashFlows_Inflation.at(iYear) = m_cashFlows_Inflation.at(iYear) - PVIF * ( ( pow( 1 + m_OMInflation, iYear ) * ( m_RefCostObjsData.at(j)->fixedOM() + m_RefCostObjsData.at(j)->variableOM() ) ) );
          m_cashFlows_Capital_Inflation.at(iYear) = m_cashFlows_Capital_Inflation.at(iYear) - PVIF * ( ( pow( 1 + m_OMInflation, iYear ) * ( m_RefCostObjsData.at(j)->fixedOM() + m_RefCostObjsData.at(j)->variableOM() ) ) );
        }
        if ( m_RefCostObjsData.at(j)->expectedLife() != 0 ) 
        {
          if ( ( iYear % m_RefCostObjsData.at(j)->expectedLife() == 0 ) && ( analysisPeriod != iYear ) ) 
          {
            m_cashFlows.at(iYear) = m_cashFlows.at(iYear) + m_RefCostObjsData.at(j)->salvageCost() - m_RefCostObjsData.at(j)->matCost() - m_RefCostObjsData.at(j)->installCost();
            m_cashFlows_Inflation.at(iYear) = m_cashFlows_Inflation.at(iYear) + PVIF * ( ( pow( 1 + m_inflation, iYear ) * ( m_RefCostObjsData.at(j)->salvageCost() ) ) - ( pow( 1 + m_inflation, iYear ) * ( m_RefCostObjsData.at(j)->matCost() + m_RefCostObjsData.at(j)->installCost() ) ) );
            m_cashFlows_Capital_Inflation.at(iYear) = m_cashFlows_Capital_Inflation.at(iYear) + PVIF * ( ( pow( 1 + m_inflation, iYear ) * ( m_RefCostObjsData.at(j)->salvageCost() ) ) - ( pow( 1 + m_inflation, iYear ) * ( m_RefCostObjsData.at(j)->matCost() + m_RefCostObjsData.at(j)->installCost() ) ) );
          }
        } //if expectedlife != 0
      }
    } //for j
  } //for iYear
}
Beispiel #12
0
 double elapsed_min() const            // return minimum value for elapsed()
 {
     return double(1)/double(CLOCKS_PER_SEC);
 }
Beispiel #13
0
 double elapsed() const                  // return elapsed time in seconds
 {
     return  double(std::clock() - _start_time) / CLOCKS_PER_SEC;
 }
Beispiel #14
0
	bool intersection(const rectangle & r, point pos_beg, point pos_end, point& good_pos_beg, point& good_pos_end)
	{
		const int right = r.right();
		const int bottom = r.bottom();

		if(pos_beg.x > pos_end.x)
			std::swap(pos_beg, pos_end);

		bool good_beg = (0 <= pos_beg.x && pos_beg.x < right && 0 <= pos_beg.y && pos_beg.y < bottom);
		bool good_end = (0 <= pos_end.x && pos_end.x < right && 0 <= pos_end.y && pos_end.y < bottom);


		if(good_beg && good_end)
		{
			good_pos_beg = pos_beg;
			good_pos_end = pos_end;
			return true;
		}
		else if(pos_beg.x == pos_end.x)
		{
			if(r.x <= pos_beg.x && pos_beg.x < right)
			{
				if(pos_beg.y < r.y)
				{
					if(pos_end.y < r.y)
						return false;
					good_pos_beg.y = r.y;
					good_pos_end.y = (pos_end.y < bottom ? pos_end.y  : bottom - 1);
				}
				else if(pos_beg.y >= bottom)
				{
					if(pos_end.y >= bottom)
						return false;
					good_pos_beg.y = bottom - 1;
					good_pos_end.y = (pos_end.y < r.y ? r.y : pos_end.y);
				}

				good_pos_beg.x = good_pos_end.x = r.x;
				return true;
			}
			return false;
		}
		else if(pos_beg.y == pos_end.y)
		{
			if(r.y <= pos_beg.y && pos_beg.y < bottom)
			{
				if(pos_beg.x < r.x)
				{
					if(pos_end.x < r.x)
						return false;
					good_pos_beg.x = r.x;
					good_pos_end.x = (pos_end.x < right ? pos_end.x : right - 1);
				}
				else if(pos_beg.x >= right)
				{
					if(pos_end.x >= right)
						return false;

					good_pos_beg.x = right - 1;
					good_pos_end.x = (pos_end.x < r.x ? r.x : pos_end.x);
				}
				good_pos_beg.y = good_pos_end.y = r.y;
				return true;
			}
			return false;
		}

		double m = (pos_end.y - pos_beg.y ) / double(pos_end.x - pos_beg.x);
		bool is_nw_to_se = (m >= 0.0);
		//The formulas for the line.
		//y = m * (x - pos_beg.x) + pos_beg.y
		//x = (y - pos_beg.y) / m + pos_beg.x
		if(!good_beg)
		{
			good_pos_beg.y = static_cast<int>(m * (r.x - pos_beg.x)) + pos_beg.y;
			if(r.y <= good_pos_beg.y && good_pos_beg.y < bottom)
			{
				good_pos_beg.x = r.x;
			}
			else
			{
				bool cond;
				int y;
				if(is_nw_to_se)
				{
					y = r.y;
					cond = good_pos_beg.y < y;
				}
				else
				{
					y = bottom - 1;
					cond = good_pos_beg.y > y;
				}

				if(cond)
				{
					good_pos_beg.x = static_cast<int>((y - pos_beg.y) / m) + pos_beg.x;
					if(r.x <= good_pos_beg.x && good_pos_beg.x < right)
						good_pos_beg.y = y;
					else
						return false;
				}
				else
					return false;
			}

			if(good_pos_beg.x < pos_beg.x)
				return false;
		}
		else
			good_pos_beg = pos_beg;

		if(!good_end)
		{
			good_pos_end.y = static_cast<int>(m * (right - 1 - pos_beg.x)) + pos_beg.y;
			if(r.y <= good_pos_end.y && good_pos_end.y < bottom)
			{
				good_pos_end.x = right - 1;
			}
			else
			{
				bool cond;
				int y;
				if(is_nw_to_se)
				{
					y = bottom - 1;
					cond = good_pos_end.y > y;
				}
				else
				{
					y = r.y;
					cond = good_pos_end.y < y;
				}

				if(cond)
				{
					good_pos_end.x = static_cast<int>((y - pos_beg.y) / m) + pos_beg.x;
					if(r.x <= good_pos_end.x && good_pos_end.x < right)
						good_pos_end.y = y;
					else
						return false;
				}
				else
					return false;
			}
			if(good_pos_end.x > pos_end.x)
				return false;
		}
		else
			good_pos_end = pos_end;

		return true;
	}
Beispiel #15
0
int __cdecl __fpclassify (float x) {
   return _fpclass(double(x));
}
int main(int argc, char *argv[])
{
  Pooma::initialize(argc,argv);
  Pooma::Tester tester(argc,argv);
  tester.out().setOutputContext(-1);

  int myContext = Pooma::context();
  int numContexts = Pooma::contexts();

  // Create the total domain.

  Interval<1> x(12);
  
  Array<1, double, Remote<Dynamic> > a(x);

  // Store some stuff.
  
  int i;
  for (i = 0; i < 12; ++i)
  {
     a(i) = double(i);
  }

  tester.out() << " Array a = " << a << std::endl;

#if POOMA_CHEETAH

  IndirectionList<int> list(5);

  list(0) = 3;
  list(1) = 5;
  list(2) = 7;
  list(3) = 8;
  list(4) = 9;

  if (myContext == 0)
  {
    int size = a.engine().packSize(list);

    char *buffer = new char [size];

    a.engine().pack(list, buffer, false);

    a.engine().unpack(Interval<1>(7, 11), buffer, false);

    delete [] buffer;
  }

  tester.out() << " Array a = " << a << std::endl;

  if (numContexts > 1)
  {
    // Create an engine on another context...
    Engine<1, double, Remote<Dynamic> > eng(1, x);
    Array<1, double, Remote<Dynamic> > b(eng);

    b = 0;
    Pooma::blockAndEvaluate();

    if (myContext == 0)
    {
      PackObject pack(a, list);
      int toContext = 1;
      int tag = Pooma::sendTag(toContext);
      tester.out() << "Sending data to context " << toContext
                   << " with tag " << tag << std::endl;
      Pooma::particleSwapHandler()->send(toContext, tag, pack);
    }
    if (myContext == 1)
    {
      int fromContext = 0;
      int tag = Pooma::receiveTag(fromContext);
      tester.out() << "Receiving data from context " << fromContext
                   << " with tag " << tag << std::endl;
      Pooma::particleSwapHandler()->request(fromContext, tag,
					    unpackFunction, &b);

      while (!ready_g)
      {
	Pooma::poll();
      }
    }

    tester.out() << b << std::endl;
  }

#endif

  int ret = tester.results("remoteDynamicTest1");
  Pooma::finalize();
  return 0;
}
Beispiel #17
0
void
BoxLib::Initialize (int& argc, char**& argv, bool build_parm_parse, MPI_Comm mpi_comm)
{
    ParallelDescriptor::StartParallel(&argc, &argv, mpi_comm);

#ifndef WIN32
    //
    // Make sure to catch new failures.
    //
    std::set_new_handler(BoxLib::OutOfMemory);

    if (argv[0][0] != '/') {
	char temp[1024];
	getcwd(temp,1024);
	exename = temp;
	exename += "/";
    }
    exename += argv[0];
#endif

#ifdef BL_USE_UPCXX
    upcxx::init(&argc, &argv);
    if (upcxx::myrank() != ParallelDescriptor::MyProc())
	BoxLib::Abort("UPC++ rank != MPI rank");
#endif

#ifdef BL_USE_MPI3
    MPI_Win_create_dynamic(MPI_INFO_NULL, MPI_COMM_WORLD, &ParallelDescriptor::cp_win);
    MPI_Win_create_dynamic(MPI_INFO_NULL, MPI_COMM_WORLD, &ParallelDescriptor::fb_win);
    MPI_Win_create_dynamic(MPI_INFO_NULL, MPI_COMM_WORLD, &ParallelDescriptor::fpb_win);
#endif

    while (!The_Initialize_Function_Stack.empty())
    {
        //
        // Call the registered function.
        //
        (*The_Initialize_Function_Stack.top())();
        //
        // And then remove it from the stack.
        //
        The_Initialize_Function_Stack.pop();
    }

    if(ParallelDescriptor::NProcsSidecar() > 0) {
      if(ParallelDescriptor::InSidecarGroup()) {
        if (ParallelDescriptor::IOProcessor())
          std::cout << "===== SIDECARS INITIALIZED =====" << std::endl;
        ParallelDescriptor::SidecarProcess();
        BoxLib::Finalize();
        return;
      }
    }

    BL_PROFILE_INITIALIZE();

    //
    // Initialize random seed after we're running in parallel.
    //
    BoxLib::InitRandom(ParallelDescriptor::MyProc()+1, ParallelDescriptor::NProcs());

#ifdef BL_USE_MPI
    if (ParallelDescriptor::IOProcessor())
    {
        std::cout << "MPI initialized with "
                  << ParallelDescriptor::NProcs()
                  << " MPI processes\n";
    }
#endif

#ifdef _OPENMP
    if (ParallelDescriptor::IOProcessor())
    {
        std::cout << "OMP initialized with "
                  << omp_get_max_threads()
                  << " OMP threads\n";
    }
#endif

    signal(SIGSEGV, BLBackTrace::handler); // catch seg falult
    signal(SIGINT,  BLBackTrace::handler);

#ifndef BL_AMRPROF
    if (build_parm_parse)
    {
        if (argc == 1)
        {
            ParmParse::Initialize(0,0,0);
        }
        else
        {
            if (strchr(argv[1],'='))
            {
                ParmParse::Initialize(argc-1,argv+1,0);
            }
            else
            {
                ParmParse::Initialize(argc-2,argv+2,argv[1]);
            }
        }
    }

    {
	ParmParse pp("boxlib");
	pp.query("v", verbose);
	pp.query("verbose", verbose);

	int invalid = 0, divbyzero=0, overflow=0;
	pp.query("fpe_trap_invalid", invalid);
	pp.query("fpe_trap_zero", divbyzero);
	pp.query("fpe_trap_overflow", overflow);
	int flags = 0;
	if (invalid)   flags |= FE_INVALID;
	if (divbyzero) flags |= FE_DIVBYZERO;
	if (overflow)  flags |= FE_OVERFLOW;
#if defined(__linux__)
#if !defined(__PGI) || (__PGIC__ >= 16)
	if (flags != 0) {
	    feenableexcept(flags);  // trap floating point exceptions
	    signal(SIGFPE,  BLBackTrace::handler);
	}
#endif
#endif
    }

    ParallelDescriptor::StartTeams();

    mempool_init();

#endif

    std::cout << std::setprecision(10);

    if (double(std::numeric_limits<long>::max()) < 9.e18)
    {
	if (ParallelDescriptor::IOProcessor())
	{
	    std::cout << "!\n! WARNING: Maximum of long int, "
		      << std::numeric_limits<long>::max() 
		      << ", might be too small for big runs.\n!\n";
	}
    }

#if defined(BL_USE_FORTRAN_MPI) || defined(BL_USE_F_INTERFACES)
    int fcomm = MPI_Comm_c2f(ParallelDescriptor::Communicator());
    bl_fortran_mpi_comm_init (fcomm);
#endif

#if defined(BL_MEM_PROFILING) && defined(BL_USE_F_BASELIB)
    MemProfiler_f::initialize();
#endif
}
int main(void)
{
  double y[EQ_N][2];
  double (*func[EQ_N])();
  double parameter[PARTICLE_N][PARA_N], parameter_memory[PARA_N], resampled_parameter[PARTICLE_N][PARA_N];
  double ref_parameter[PARA_N];
  double time_point[TIME_POINT_N];
  double ref_time_point[TIME_POINT_N];

  int i, j, k, l, m;
  int mcmc_num, pa_num, integral_num, particle_num, rk_num, timepoint_num, parameter_num, equation_num;
  
  int x_flag = 0;
  double dt;

  double probability_before, probability_after, probability_ratio;
  int move_count = 0;

  double weight[PARTICLE_N], weight_tmp[PARTICLE_N];
  double total_weight = 0, power_total_weight, partial_total_weight, upper_weight, lower_weight;
  double log_weight[PARTICLE_N], log_weight_tmp[PARTICLE_N];
  double total_likelihood[PARTICLE_N], total_likelihood_previous[PARTICLE_N];
  double log_likelihood[PARTICLE_N], total_log_likelihood;
  double epsilon[POPULATION_N] = {1.5, 1.0, 0.75, 0.5, 0.25, 0.1, 0.09, 0.08, 0.07, 0.06, 0.05, 0.04, 0.03, 0.02, 0.01};
  double ess;
  int sampling_num;
  int resampling_count = 0;
  int weighten_particle_num[POPULATION_N] = {0, 0, 0, 0, 0}, last_weighten_particle_num = 0;
  int resampling_flag[POPULATION_N] = {0, 0, 0, 0, 0};

  double effective_particle_num = 0, total_effective_particle_num = 0;
  double weighten_particle_multiplier = 1;

  int mcmc_step;

  double unit_r, chosen_num;

  FILE *fp1, *fp2, *fp3, *fp4, *fp5, *fp6, *fp7, *fin;

  clock_t start, end;

  dt = 0.001;


  function_set(func);


/*** 計算開始 **********************************************************************************************************************************/

  /* 時間を計る */
  start = clock();
  
  /* 乱数の初期化 */
  init_genrand(2);

  /* ファイル設定 */
  fp1 = fopen("information2.data","w");

  /* 実験データの読み込み */
  fin = fopen("ref_time_point.data","r");

  for(timepoint_num=0;timepoint_num<TIME_POINT_N;timepoint_num++){
    fscanf(fin, "%lf", &ref_time_point[timepoint_num]);
  }

  fclose(fin);
  /* 実験データの読み込み終了 */


  /* 参照パラメータ値設定 */
  parameter_set(ref_parameter);

  /* サンプル番号初期化 */
  sampling_num = 0;

  printf("0 th population\n");

  /* ランダムサンプリングによる 粒子数個のパラメータセットの発生 **************************************************************************************/
  for( ; ; ){
    /* パラメータを発生させる */
    parameter_set(parameter[sampling_num]);
    parameter_generation(parameter[sampling_num], ref_parameter);

    sampling_num++;
    
    if(sampling_num == PARTICLE_N) break; 
  }


  /* 重みを初期化 正規化 */
  for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
    weight[particle_num] = 1.0/PARTICLE_N;
  }
  /* ランダムサンプリングによる初期パラメータ発生 終了 ************************************************************************************************/









  
  /* Population annealing 開始 *****************************************************************************************************************/
  for(pa_num=0;pa_num<POPULATION_N;pa_num++){

    printf("%d th population\n", pa_num+1);
    
    /* 各粒子ごとに尤度の計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      total_likelihood[particle_num] = 0; /* 初期化 */
      total_likelihood_previous[particle_num] = 0; /* 初期化 */
    }


    /* 中間分布の計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){

      /* time point データの発生 */
      initial_condition_set(y);
      rk_search(1, dt, func, y, parameter[particle_num], time_point);

      /* 尤度の計算 */
      total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]);

      if(pa_num==0){
        total_likelihood_previous[particle_num] = 1;
      }
      else{
        total_likelihood_previous[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num-1]);
      }

    }
    /* 中間分布の計算終了 */


    /* 重みの計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      weight[particle_num] = weight[particle_num] * total_likelihood[particle_num]/total_likelihood_previous[particle_num];
      if(total_likelihood[particle_num]==0 || total_likelihood_previous[particle_num]==0) weight[particle_num] = 0.0;
    }

    total_weight = 0.0;

    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      total_weight = total_weight + weight[particle_num];
    }
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      weight[particle_num] = weight[particle_num]/total_weight;
    }


    /* 重みを持つ粒子数の計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      if(weight[particle_num]!=0) weighten_particle_num[pa_num]++;
    }
    fprintf(fp1, "weighten particle num = %d\n", weighten_particle_num[pa_num]);





    /* 各粒子ごとに */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){

      /* 重みが0なら飛ばす */
      if(weight[particle_num]==0) continue;

      /* フラグの初期化 */
      x_flag = 0;


      /* MCMC 計算 */
      for(mcmc_num=0;mcmc_num<MCMC_MAX_STEP;mcmc_num++){
 
        /* 許容されなければ、元のままのパラメータ */
        if(x_flag == 1){
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
        }


        /* 確率の初期化 */
        probability_before = 1.0;
        probability_after = 1.0;
    

        /* フラグの初期化 */
        x_flag = 0;


        /* 新候補の計算前の値を記憶 */
        for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
          parameter_memory[parameter_num] = parameter[particle_num][parameter_num];
        }


        /* 移動前の確率を計算 */
        probability_before = probability_before*pdf_uniform_parameter(parameter[particle_num], ref_parameter); /* 事前分布を乗じる */

        
        total_likelihood[particle_num] = 0.0; /* 初期化 */

        /* time point データの発生 */
        initial_condition_set(y);
        rk_search(1, dt, func, y, parameter[particle_num], time_point);

        /* 尤度の計算 */
        total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]);

        probability_before = probability_before * total_likelihood[particle_num]; /* 移動前の確率 */  


        /* 新候補を計算 パラメータの中から1つだけ動かす */
        parameter_sampler(parameter[particle_num]);


        /* 移動後の確率を計算 : 一様事前分布を乗じる */
        probability_after = probability_after*pdf_uniform_parameter(parameter[particle_num], ref_parameter); /* 事前分布を乗じる */
        

        if(probability_after == 0.0){
          x_flag = 1;
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
          continue;
        }



        /* 移動後の確率を計算 */
        total_likelihood[particle_num] = 0.0; /* 初期化 */

        /* time point データの発生 */
        initial_condition_set(y);
        rk_search(1, dt, func, y, parameter[particle_num], time_point);

        /* 尤度の計算 */
        total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]);

        probability_after = probability_after * total_likelihood[particle_num]; /* 移動後の確率 */


        if(probability_after == 0.0){
          x_flag = 1;
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
          continue;
        }



        /* 移動前と移動後の確率の比の計算 */
        probability_ratio = probability_after/probability_before;

        /* [0,1) 単位乱数の発生 */
        unit_r = genrand_real2();   


        /* 移動の判定 */
        if(probability_ratio > unit_r){ 
          move_count++;
        }
        else{
          x_flag = 1;
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
          continue;
        }
    
      }
      /* particle_num 番目の粒子の MCMC 終了 */
    }
    /* 全粒子の MCMC 終了 */
 




 
    /* リサンプリング ********************************************************/
    power_total_weight = 0.0;
    ess = 0.0;

    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      power_total_weight = power_total_weight + pow(weight[particle_num], 2);
    }


    /* Effective Sample Size の計算 */
    ess = 1.0/power_total_weight;
    //if(pa_num==4) ess = 0.0;

    fprintf(fp1, "%d th population", pa_num);
    fprintf(fp1, "ESS = %f\t particle_num/2 = %f\n\n", ess, PARTICLE_N/2.0);
    

    /* リサンプリングの判定と実行 */
    if(ess < PARTICLE_N/2){

      fprintf(fp1, "resampling\n");
      resampling_count++;
      resampling_flag[pa_num] = 1;
      fprintf(fp1, "resampling flag = %d\n", resampling_flag[pa_num]);
      
      /* 粒子数個リサンプリングする 重複可 */
      for(m=0;m<PARTICLE_N;m++){

        /* [0,1) 乱数発生 */
        unit_r = genrand_real2();

        partial_total_weight = 0.0;

        /* l 番目の粒子が選ばれる */
        for(l=0;l<PARTICLE_N;l++){
          partial_total_weight = partial_total_weight + weight[l];

          upper_weight = partial_total_weight;
          lower_weight = partial_total_weight - weight[l];

          if((unit_r >= lower_weight) && (unit_r < upper_weight)){
            for(i=0;i<PARA_N;i++){
              resampled_parameter[m][i] = parameter[l][i];
            }
            break;
          }
        }

      }
      /* 粒子数個リサンプリング終了 */



      /* リサンプル後のパラメータと活性化時間の再設定 */
      for(l=0;l<PARTICLE_N;l++){
        for(i=0;i<PARA_N;i++){
          parameter[l][i] = resampled_parameter[l][i];
        }
      }



      /* リサンプル後の重みを初期化 正規化 */
      for(l=0;l<PARTICLE_N;l++){
        weight[l] = 1.0/PARTICLE_N;
      }


    }
    /* リサンプリングの判定と実行 終了 */
    /* リサンプリング終了 ****************************************************/

  }
  /* Population annealing 終了 *****************************************************************************************************************/
  

  for(pa_num=0;pa_num<POPULATION_N;pa_num++){
    if(resampling_flag[pa_num]==1){
      weighten_particle_multiplier = weighten_particle_multiplier * weighten_particle_num[pa_num]/PARTICLE_N;
    }
  }

  /* 重みを持つ粒子数の計算 */
  last_weighten_particle_num = 0;
  for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
    if(weight[particle_num]!=0) last_weighten_particle_num++;
  }
  effective_particle_num = last_weighten_particle_num*weighten_particle_multiplier;
  
  fprintf(fp1, "effective particle number = %f\n", effective_particle_num);



  /* 移動回数、 リサンプリング回数、 モデル数を出力 */
  fprintf(fp1, "%d times move\n", move_count);
  fprintf(fp1, "%d times resampling\n", resampling_count);
  end = clock();
  /* 計算時間の出力 */
  fprintf(fp1, "%f min\n", (double)(end - start)/CLOCKS_PER_SEC/60.0);



  fclose(fp1);

  return 0;
}
void QFRDRImagingFCSCountrateDisplay::displayData() {
    if (!avgGraph) return;
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    QFRDRImagingFCSData* m=qobject_cast<QFRDRImagingFCSData*>(current);
    JKQTPdatastore* ds=ui->pltIntensity->get_plotter()->getDatastore();
    data=NULL;
    dataN=0;
    dataT=NULL;
    ui->pltIntensity->get_plotter()->clearOverlayElement(true);
    avgIndicator=new JKQTPoverlayVerticalLine(0, ui->pltIntensity->get_plotter());
    ui->pltIntensity->get_plotter()->addOverlayElement(avgIndicator);
    if (!current || !m) {
        ds->clear();
        ui->pltIntensity->set_doDrawing(false);

        avgGraph->set_xColumn(-1);
        avgGraph->set_yColumn(-1);
        avgGraph->set_xErrorColumn(-1);
        avgGraph->set_yErrorColumn(-1);


        ui->pltIntensity->zoomToFit();
        ui->pltIntensity->set_doDrawing(true);
        ui->pltIntensity->update_plot();
        ui->edtData->clear();
        ui->labInfo->clear();
    } else {

        JKQTPdatastore* ds=ui->pltIntensity->get_plotter()->getDatastore();
        ds->clear();
        ui->pltIntensity->set_doDrawing(false);
        double duration=m->getMeasurementDuration();
        double exposure=m->getFrameTime();
        int segments=m->getSegmentCount();
        int sumframes=m->getProperty("VIDEO_AVGFRAMES", 0).toInt();

        int colT=ds->addColumn(m->getStatisticsT(), m->getStatisticsN(), "time");
        int colAvg=ds->addColumn(m->getStatisticsMean(), m->getStatisticsN(), "avg");
        int colStddev=ds->addColumn(m->getStatisticsStdDev(), m->getStatisticsN(), "stddev");
        int colMin=ds->addColumn(m->getStatisticsMin(), m->getStatisticsN(), "min");
        int colMax=ds->addColumn(m->getStatisticsMax(), m->getStatisticsN(), "max");
        int bcolT=ds->addColumn(m->getBackgroundStatisticsT(), m->getBackgroundStatisticsN(), "back time");
        int bcolAvg=ds->addColumn(m->getBackgroundStatisticsMean(), m->getBackgroundStatisticsN(), "back avg");
        int bcolStddev=ds->addColumn(m->getBackgroundStatisticsStdDev(), m->getBackgroundStatisticsN(), "back stddev");
        int bcolMin=ds->addColumn(m->getBackgroundStatisticsMin(), m->getBackgroundStatisticsN(), "back min");
        int bcolMax=ds->addColumn(m->getBackgroundStatisticsMax(), m->getBackgroundStatisticsN(), "back max");

        int ucolT=ds->addColumn(m->getUncorrectedStatisticsT(), m->getUncorrectedStatisticsN(), "uncorrected time");
        int ucolAvg=ds->addColumn(m->getUncorrectedStatisticsMean(), m->getUncorrectedStatisticsN(), "uncorrected avg");
        int ucolStddev=ds->addColumn(m->getUncorrectedStatisticsStdDev(), m->getUncorrectedStatisticsN(), "uncorrected stddev");
        int ucolMin=ds->addColumn(m->getUncorrectedStatisticsMin(), m->getUncorrectedStatisticsN(), "uncorrected min");
        int ucolMax=ds->addColumn(m->getUncorrectedStatisticsMax(), m->getUncorrectedStatisticsN(), "uncorrected max");

        double varAvg=0;
        double meanAvg=statisticsAverageVariance(varAvg, m->getStatisticsMean(), m->getStatisticsN());
        double varStddev=0;
        double meanStddev=statisticsAverageVariance(varStddev, m->getStatisticsStdDev(), m->getStatisticsN());
        double varMin=0;
        double meanMin=statisticsAverageVariance(varMin, m->getStatisticsMin(), m->getStatisticsN());
        double varMax=0;
        double meanMax=statisticsAverageVariance(varMax, m->getStatisticsMax(), m->getStatisticsN());

        double bvarAvg=0;
        double bmeanAvg=statisticsAverageVariance(bvarAvg, m->getBackgroundStatisticsMean(), m->getBackgroundStatisticsN());
        double bvarStddev=0;
        double bmeanStddev=statisticsAverageVariance(bvarStddev, m->getBackgroundStatisticsStdDev(), m->getBackgroundStatisticsN());
        double bvarMin=0;
        double bmeanMin=statisticsAverageVariance(bvarMin, m->getBackgroundStatisticsMin(), m->getBackgroundStatisticsN());
        double bvarMax=0;
        double bmeanMax=statisticsAverageVariance(bvarMax, m->getBackgroundStatisticsMax(), m->getBackgroundStatisticsN());

        double uvarAvg=0;
        double umeanAvg=statisticsAverageVariance(uvarAvg, m->getUncorrectedStatisticsMean(), m->getUncorrectedStatisticsN());
        double uvarStddev=0;
        double umeanStddev=statisticsAverageVariance(uvarStddev, m->getUncorrectedStatisticsStdDev(), m->getUncorrectedStatisticsN());
        double uvarMin=0;
        double umeanMin=statisticsAverageVariance(uvarMin, m->getUncorrectedStatisticsMin(), m->getUncorrectedStatisticsN());
        double uvarMax=0;
        double umeanMax=statisticsAverageVariance(uvarMax, m->getUncorrectedStatisticsMax(), m->getUncorrectedStatisticsN());

        double dispMean=0, dispStddev=0;

        if (ui->cmbGraph->currentIndex()<=5) {
            dataT=m->getStatisticsT();
        } else if (ui->cmbGraph->currentIndex()<=11) {
            dataT=m->getBackgroundStatisticsT();
        } else {
            dataT=m->getUncorrectedStatisticsT();
        }

        if (ui->cmbGraph->currentIndex()==0) {
            avgGraph->set_xColumn(colT);
            avgGraph->set_yColumn(colAvg);
            avgGraph->set_yErrorColumn(colStddev);
            avgGraph->set_title(tr("avg \\pm stddev"));
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            dispMean=meanAvg; dispStddev=sqrt(varAvg);
            data=m->getStatisticsMean();
            dataN=m->getStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==1) {
            avgGraph->set_xColumn(colT);
            avgGraph->set_yColumn(colAvg);
            avgGraph->set_yErrorColumn(colStddev);
            minGraph->set_xColumn(colT);
            minGraph->set_yColumn(colMin);
            maxGraph->set_xColumn(colT);
            maxGraph->set_yColumn(colMax);
            avgGraph->set_title(tr("avg \\pm stddev"));
            minGraph->set_title(tr("minimum"));
            maxGraph->set_title(tr("maximum"));
            dispMean=meanAvg; dispStddev=sqrt(varAvg);
            data=m->getStatisticsMean();
            dataN=m->getStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==2) {
            avgGraph->set_xColumn(colT);
            avgGraph->set_yColumn(colAvg);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("average"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=meanAvg; dispStddev=sqrt(varAvg);
            data=m->getStatisticsMean();
            dataN=m->getStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==3) {
            avgGraph->set_xColumn(colT);
            avgGraph->set_yColumn(colStddev);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("stddev"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=meanStddev; dispStddev=sqrt(varStddev);
            data=m->getStatisticsStdDev();
            dataN=m->getStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==4) {
            avgGraph->set_xColumn(colT);
            avgGraph->set_yColumn(colMin);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("minimum"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=meanMin; dispStddev=sqrt(varMin);
            data=m->getStatisticsMin();
            dataN=m->getStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==5) {
            avgGraph->set_xColumn(colT);
            avgGraph->set_yColumn(colMax);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("maximum"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=meanMax; dispStddev=sqrt(varMax);
            data=m->getStatisticsMax();
            dataN=m->getStatisticsN();







        } else if (ui->cmbGraph->currentIndex()==6) {
            avgGraph->set_xColumn(bcolT);
            avgGraph->set_yColumn(bcolAvg);
            avgGraph->set_yErrorColumn(bcolStddev);
            avgGraph->set_title(tr("avg \\pm stddev"));
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            dispMean=bmeanAvg; dispStddev=sqrt(bvarAvg);
            data=m->getBackgroundStatisticsMean();
            dataN=m->getBackgroundStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==7) {
            avgGraph->set_xColumn(bcolT);
            avgGraph->set_yColumn(bcolAvg);
            avgGraph->set_yErrorColumn(bcolStddev);
            minGraph->set_xColumn(bcolT);
            minGraph->set_yColumn(bcolMin);
            maxGraph->set_xColumn(bcolT);
            maxGraph->set_yColumn(bcolMax);
            avgGraph->set_title(tr("avg \\pm stddev"));
            minGraph->set_title(tr("minimum"));
            maxGraph->set_title(tr("maximum"));
            dispMean=bmeanAvg; dispStddev=sqrt(bvarAvg);
            data=m->getBackgroundStatisticsMean();
            dataN=m->getBackgroundStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==8) {
            avgGraph->set_xColumn(bcolT);
            avgGraph->set_yColumn(bcolAvg);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("average"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=bmeanAvg; dispStddev=sqrt(bvarAvg);
            data=m->getBackgroundStatisticsMean();
            dataN=m->getBackgroundStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==9) {
            avgGraph->set_xColumn(bcolT);
            avgGraph->set_yColumn(bcolStddev);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("stddev"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=bmeanStddev; dispStddev=sqrt(bvarStddev);
            data=m->getBackgroundStatisticsStdDev();
            dataN=m->getBackgroundStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==10) {
            avgGraph->set_xColumn(bcolT);
            avgGraph->set_yColumn(bcolMin);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("minimum"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=bmeanMin; dispStddev=sqrt(bvarMin);
            data=m->getBackgroundStatisticsMin();
            dataN=m->getBackgroundStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==11) {
            avgGraph->set_xColumn(bcolT);
            avgGraph->set_yColumn(bcolMax);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("maximum"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=bmeanMax; dispStddev=sqrt(bvarMax);
            data=m->getBackgroundStatisticsMax();
            dataN=m->getBackgroundStatisticsN();




        } else if (ui->cmbGraph->currentIndex()==12) {
            avgGraph->set_xColumn(ucolT);
            avgGraph->set_yColumn(ucolAvg);
            avgGraph->set_yErrorColumn(ucolStddev);
            avgGraph->set_title(tr("avg \\pm stddev"));
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            dispMean=bmeanAvg; dispStddev=sqrt(uvarAvg);
            data=m->getUncorrectedStatisticsMean();
            dataN=m->getUncorrectedStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==13) {
            avgGraph->set_xColumn(ucolT);
            avgGraph->set_yColumn(ucolAvg);
            avgGraph->set_yErrorColumn(ucolStddev);
            minGraph->set_xColumn(ucolT);
            minGraph->set_yColumn(ucolMin);
            maxGraph->set_xColumn(ucolT);
            maxGraph->set_yColumn(ucolMax);
            avgGraph->set_title(tr("avg \\pm stddev"));
            minGraph->set_title(tr("minimum"));
            maxGraph->set_title(tr("maximum"));
            dispMean=umeanAvg; dispStddev=sqrt(uvarAvg);
            data=m->getUncorrectedStatisticsMean();
            dataN=m->getUncorrectedStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==14) {
            avgGraph->set_xColumn(ucolT);
            avgGraph->set_yColumn(ucolAvg);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("average"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=umeanAvg; dispStddev=sqrt(uvarAvg);
            data=m->getUncorrectedStatisticsMean();
            dataN=m->getUncorrectedStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==15) {
            avgGraph->set_xColumn(ucolT);
            avgGraph->set_yColumn(ucolStddev);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("stddev"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=umeanStddev; dispStddev=sqrt(uvarStddev);
            data=m->getUncorrectedStatisticsStdDev();
            dataN=m->getUncorrectedStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==16) {
            avgGraph->set_xColumn(ucolT);
            avgGraph->set_yColumn(ucolMin);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("minimum"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=umeanMin; dispStddev=sqrt(uvarMin);
            data=m->getUncorrectedStatisticsMin();
            dataN=m->getUncorrectedStatisticsN();
        } else if (ui->cmbGraph->currentIndex()==17) {
            avgGraph->set_xColumn(ucolT);
            avgGraph->set_yColumn(ucolMax);
            avgGraph->set_yErrorColumn(-1);
            minGraph->set_xColumn(-1);
            minGraph->set_yColumn(-1);
            maxGraph->set_xColumn(-1);
            maxGraph->set_yColumn(-1);
            avgGraph->set_title(tr("maximum"));
            minGraph->set_title("");
            maxGraph->set_title("");
            dispMean=umeanMax; dispStddev=sqrt(uvarMax);
            data=m->getUncorrectedStatisticsMax();
            dataN=m->getUncorrectedStatisticsN();
        }

        if (duration>0 && segments>0) {

            for (int i=0; i<segments; i++) {
                double t=double(i)*duration/double(segments);
                if (m->segmentUsed(i)) {
                    JKQTPoverlayVerticalLine* ovl=new JKQTPoverlayVerticalLine(t, tr("seg.%1  t=%2s").arg(i+1).arg(t), ui->pltIntensity->get_plotter());
                    ovl->set_color(QColor("black"));
                    ovl->set_lineWidth(2);
                    ovl->set_lineStyle(Qt::DotLine);
                    ovl->set_fontSize(9);
                    ui->pltIntensity->get_plotter()->addOverlayElement(ovl);
                } else {
                    JKQTPoverlayVerticalRange* ovl=new JKQTPoverlayVerticalRange(t, t+duration/double(segments), tr("seg.%1  t=%2s").arg(i+1).arg(t), ui->pltIntensity->get_plotter());
                    QColor fill=QColor("darkgray");
                    fill.setAlphaF(0.6);
                    ovl->set_color(QColor("darkgray"));
                    ovl->set_fillColor(fill);
                    ovl->set_lineWidth(2);
                    ovl->set_lineStyle(Qt::DotLine);
                    ovl->set_fontSize(9);
                    ui->pltIntensity->get_plotter()->addOverlayElement(ovl);
                }
            }
        }

        rangeGraph->set_rangeCenter(dispMean);
        rangeGraph->set_rangeMin(dispMean-dispStddev);
        rangeGraph->set_rangeMax(dispMean+dispStddev);
        ui->pltIntensity->zoomToFit();
        ui->pltIntensity->set_doDrawing(true);
        ui->pltIntensity->update_plot();
        ui->edtData->setText(current->getProperty("imfcs_crddisplay_fitresults", QString("")).toString());
        ui->labInfo->setText(tr("<table width=\"95%\"><tr><td>average of graph: %2</td><td>data points: %1</td></tr>"
                                "<tr><td>stddev of graph: %3</td><td>measurement duration: %4 seconds</td></tr>"
                                "<tr><td></td><td>segments: %5 &agrave; %6s</td></tr></table>").arg(m->getStatisticsN()).arg(dispMean).arg(dispStddev).arg(duration).arg(segments).arg(duration/double(segments)));
    }
    updateFitFuncPlot();
    QApplication::restoreOverrideCursor();
}
/**
 * Generates a random decimal between 0 and 1
 */
double randomReal() {
  return double(rand()) / double(RAND_MAX);
}
RockPhysicsInversion4D::RockPhysicsInversion4D(NRLib::Vector                      priorMean,
                                               NRLib::Matrix                      priorCov,
                                               NRLib::Matrix                      posteriorCov,
                                               std::vector<std::vector<double> >  mSamp)
{
  nf_.resize(4);
  nf_[0] = 60;
  nf_[1] = 60;
  nf_[2] = 60;
  nf_[3] = 60;
  nfp_= 135;

  fftplan1_ = rfftwnd_create_plan(1, &nfp_, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE | FFTW_IN_PLACE);
  fftplan2_ = rfftwnd_create_plan(1, &nfp_, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE | FFTW_IN_PLACE);

  v_.resize(4,6);
  SolveGEVProblem(priorCov,posteriorCov, v_);
  NRLib::Matrix tmp;
  NRLib::Matrix priorCovF;
  NRLib::Matrix posteriorCovF;

  meanf_        = priorMean*v_;
  tmp           = priorCov*v_;
  priorCovF     = transpose(v_)*tmp;
  tmp           = posteriorCov*v_;
  posteriorCovF = transpose(v_)*tmp;

  int nSamp = mSamp[0].size();

  NRLib::Vector m(6);
  for(int k=0;k<6;k++)
      m(k)=mSamp[k][0];

  maxf_=m*v_;
  minf_=m*v_;

  for(int i=0;i<nSamp;i++)
  {
    NRLib::Vector f;
    for(int k=0;k<6;k++)
      m(k)=mSamp[k][i];
    f=m*v_;
    for(int k=0;k<4;k++)
    {
      if(minf_(k) > f(k))
        minf_(k)=f(k);
      if(maxf_(k) < f(k))
        maxf_(k)=f(k);
    }
  }

  for(int k=0;k<4;k++)
  {
    minf_(k)-=3*sqrt(posteriorCovF(k,k));
    maxf_(k)+=3*sqrt(posteriorCovF(k,k));
  }

  smoothingFilter_.resize(4);
  priorDistribution_.resize(4);

  for(int i=0;i<4;i++)
  {
    double df=(maxf_(i)-minf_(i))/double(nf_[i]);
    priorDistribution_[i]=MakeGaussKernel(meanf_(i),priorCovF(i,i),minf_(i),df,nfp_);
    smoothingFilter_[i]=MakeSmoothingFilter(posteriorCovF(i,i),df);
  }

  allocatePredictionTables( );

  std::vector<double> dummy(nSamp);
  for(int i=0;i<nSamp;i++)
    dummy[i]=1.0;

  fillInTable( mSamp,dummy,0);
  DivideAndSmoothTable(0,priorDistribution_,smoothingFilter_);
}
int main(int argc, const char *argv[]) {
  printf("Running %s version %s\n", argv[0], version_identifier());
  for (int i=0; argv[i]; i++) {
    printf("%s ", argv[i]);
  }
  printf("\n");
  took("Starting program");
  // ----------------------------------------------------------------------------
  // Define "Constants" -- set from arguments then unchanged
  // ----------------------------------------------------------------------------

  // NOTE: debug can slow things down VERY much
  int debug = false;

  sw_simulation sw;

  sw.sticky_wall = 0;
  sw.len[0] = sw.len[1] = sw.len[2] = 1;
  sw.walls = 0;
  sw.N = 10;
  sw.translation_scale = 0.05;

  unsigned long int seed = 0;

  char *data_dir = new char[1024];
  sprintf(data_dir, "free-energy-data");
  char *filename = new char[1024];
  sprintf(filename, "default_filename");
  char *filename_suffix = new char[1024];
  sprintf(filename_suffix, "default_filename_suffix");
  long simulation_runs = 1000000;
  double acceptance_goal = .4;
  double R = 1;
  const double well_width = 1;
  double ff = 0.3;
  double ff_small = -1;
  bool force_cube=false;
  bool pack_and_save_cube=false;
  double neighbor_scale = 2;
  double de_g = 0.05;
  double max_rdf_radius = 10;
  int totime = 0;
  double scaling_factor = 1.0;
  int small_cell_check_period = (1 * sw.N * sw.N)/10;

  poptContext optCon;
  // ----------------------------------------------------------------------------
  // Set values from parameters
  // ----------------------------------------------------------------------------
  poptOption optionsTable[] = {
    {"N", '\0', POPT_ARG_INT, &sw.N, 0, "Number of balls to simulate", "INT"},
    {"ff", '\0', POPT_ARG_DOUBLE, &ff, 0, "Filling fraction. If specified, the "
     "cell dimensions are adjusted accordingly without changing the shape of "
     "the cell."},
    {"ff_small", '\0', POPT_ARG_DOUBLE, &ff_small, 0, "Small filling fraction. If specified, "
     "This sets the desired filling fraction of the shrunk cell. Otherwise it defaults to ff."},
    {"force_cube", '\0', POPT_ARG_NONE, &force_cube, 0, "forces box to be a cube", "BOOLEAN"},
    {"pack_and_save_cube", '\0', POPT_ARG_NONE, &pack_and_save_cube, 0, "packs cube, save positions, then returns", "BOOLEAN"},
    {"walls", '\0', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &sw.walls, 0,
     "Number of walled dimensions (dimension order: x,y,z)", "INT"},
    {"runs", '\0', POPT_ARG_LONG | POPT_ARGFLAG_SHOW_DEFAULT, &simulation_runs,
     0, "Number of \"runs\" for which to run the simulation", "INT"},
    {"de_g", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT, &de_g, 0,
     "Resolution of distribution functions", "DOUBLE"},
    {"max_rdf_radius", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &max_rdf_radius, 0, "Set maximum radius for RDF data collection", "DOUBLE"},
    {"lenx", '\0', POPT_ARG_DOUBLE, &sw.len[x], 0,
     "Relative cell size in x dimension", "DOUBLE"},
    {"leny", '\0', POPT_ARG_DOUBLE, &sw.len[y], 0,
     "Relative cell size in y dimension", "DOUBLE"},
    {"lenz", '\0', POPT_ARG_DOUBLE, &sw.len[z], 0,
     "Relative cell size in z dimension", "DOUBLE"},
    {"filename", '\0', POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &filename, 0,
     "Base of output file names", "STRING"},
    {"filename_suffix", '\0', POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT,
     &filename_suffix, 0, "Output file name suffix", "STRING"},
    {"data_dir", '\0', POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &data_dir, 0,
     "Directory in which to save data", "data_dir"},
    {"neighbor_scale", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &neighbor_scale, 0, "Ratio of neighbor sphere radius to interaction scale "
     "times ball radius. Drastically reduces collision detections","DOUBLE"},
    {"translation_scale", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &sw.translation_scale, 0, "Standard deviation for translations of balls, "
     "relative to ball radius", "DOUBLE"},
    {"seed", '\0', POPT_ARG_INT | POPT_ARGFLAG_SHOW_DEFAULT, &seed, 0,
     "Seed for the random number generator", "INT"},
    {"acceptance_goal", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &acceptance_goal, 0, "Goal to set the acceptance rate", "DOUBLE"},
    {"time", '\0', POPT_ARG_INT, &totime, 0,
     "Timing of display information (seconds)", "INT"},
    {"R", '\0', POPT_ARG_DOUBLE | POPT_ARGFLAG_SHOW_DEFAULT,
     &R, 0, "Ball radius (for testing purposes; should always be 1)", "DOUBLE"},
    {"debug", '\0', POPT_ARG_NONE, &debug, 0, "Debug mode", "BOOLEAN"},
    {"sf", '\0', POPT_ARG_DOUBLE, &scaling_factor, 0,
      "Factor by which to scale the small cell", "DOUBLE"},
    {"sc_period", '\0', POPT_ARG_INT, &small_cell_check_period, 0,
     "Check the small cell every P iterations", "INT"},
    POPT_AUTOHELP
    POPT_TABLEEND
  };
  optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
  poptSetOtherOptionHelp(optCon, "[OPTION...]\nNumber of balls and filling "
                         "fraction or cell dimensions are required arguments.");

  int c = 0;
  // go through arguments, set them based on optionsTable
  while((c = poptGetNextOpt(optCon)) >= 0);
  if (c < -1) {
    fprintf(stderr, "\n%s: %s\n", poptBadOption(optCon, 0), poptStrerror(c));
    return 1;
  }
  poptFreeContext(optCon);

  // ----------------------------------------------------------------------------
  // Verify we have reasonable arguments and set secondary parameters
  // ----------------------------------------------------------------------------

  if(sw.walls >= 2){
    printf("Code cannot currently handle walls in more than one dimension.\n");
    return 254;
  }
  if(sw.walls > 3){
    printf("You cannot have walls in more than three dimensions.\n");
    return 254;
  }
  if(well_width < 1){
    printf("Interaction scale should be greater than (or equal to) 1.\n");
    return 254;
  }

  if(ff_small != -1 && scaling_factor != 1.0){
    printf("You can't specify both the small filling fraction and the scaling factor.");  
    return 1;
  }


  if (ff != 0) {
    // The user specified a filling fraction, so we must make it so!
    const double volume = 4*M_PI/3*R*R*R*sw.N/ff;
    const double min_cell_width = 2*sqrt(2)*R; // minimum cell width
    const int numcells = (sw.N+3)/4; // number of unit cells we need
    const int max_cubic_width
      = pow(volume/min_cell_width/min_cell_width/min_cell_width, 1.0/3);
    if (max_cubic_width*max_cubic_width*max_cubic_width >= numcells) {
      // We can get away with a cubic cell, so let's do so.  Cubic
      // cells are nice and comfortable!
      sw.len[x] = sw.len[y] = sw.len[z] = pow(volume, 1.0/3);
    } else {
      printf("N = %d\n", sw.N);
      printf("ff = %g\n", ff);
      printf("min_cell_width = %g\n", min_cell_width);
      printf("volume**1/3 = %g\n", pow(volume, 1.0/3));
      printf("max_cubic_width**3 = %d, numcells = %d\n",
             max_cubic_width*max_cubic_width*max_cubic_width, numcells);
      // A cubic cell won't work with our initialization routine, so
      // let's go with a lopsided cell that should give us something
      // that will work.
      int xcells = int( pow(numcells, 1.0/3) );
      int cellsleft = (numcells + xcells - 1)/xcells;
      int ycells = int( sqrt(cellsleft) );
      int zcells = (cellsleft + ycells - 1)/ycells;

      // The above should give a zcells that is largest, followed by
      // ycells and then xcells.  Thus we make the lenz just small
      // enough to fit these cells, and so on, to make the cell as
      // close to cubic as possible.
      sw.len[z] = zcells*min_cell_width;
      if (xcells == ycells) {
        sw.len[x] = sw.len[y] = sqrt(volume/sw.len[z]);
      } else {
        sw.len[y] = min_cell_width*ycells;
        sw.len[x] = volume/sw.len[y]/sw.len[z];
      }
      printf("Using lopsided %d x %d x %d cell (total goal %d)\n",
             xcells, ycells, zcells, numcells);
    }
  }

  // if the user didn't specifiy a small filling fraction, then we should get it.
  if(ff_small == -1){
      ff_small = (4*M_PI/3*R*R*R*sw.N)/
        (sw.len[x]*sw.len[y]*sw.len[z]*scaling_factor*scaling_factor*scaling_factor);
  }
  // if they did, then we need to get the scale factor
  else{
    scaling_factor = std::cbrt(ff/ff_small);
  }


  printf("\nSetting cell dimensions to (%g, %g, %g).\n",
         sw.len[x], sw.len[y], sw.len[z]);
  printf("\nFilling fraction of small cell is %g", ff_small);
  if (sw.N <= 0 || simulation_runs < 0 || R <= 0 ||
      neighbor_scale <= 0 || sw.translation_scale < 0 ||
      sw.len[x] < 0 || sw.len[y] < 0 || sw.len[z] < 0) {
    fprintf(stderr, "\nAll parameters must be positive.\n");
    return 1;
  }

  const double eta = (double)sw.N*4.0/3.0*M_PI*R*R*R/(sw.len[x]*sw.len[y]*sw.len[z]);
  if (eta > 1) {
    fprintf(stderr, "\nYou're trying to cram too many balls into the cell. "
            "They will never fit. Filling fraction: %g\n", eta);
    return 7;
  }

  // If a filename was not selected, make a default
  if (strcmp(filename, "default_filename") == 0) {
    char *wall_tag = new char[100];
    if(sw.walls == 0) sprintf(wall_tag,"periodic");
    else if(sw.walls == 1) sprintf(wall_tag,"wall");
    else if(sw.walls == 2) sprintf(wall_tag,"tube");
    else if(sw.walls == 3) sprintf(wall_tag,"box");
    sprintf(filename, "%s-ww%04.2f-ff%04.2f-N%i-sf%f",
            wall_tag, well_width, eta, sw.N, scaling_factor);
    printf("\nUsing default file name: ");
    delete[] wall_tag;
  }
  else
    printf("\nUsing given file name: ");
  // If a filename suffix was specified, add it
  if (strcmp(filename_suffix, "default_filename_suffix") != 0)
    sprintf(filename, "%s-%s", filename, filename_suffix);
  printf("%s\n",filename);

  printf("------------------------------------------------------------------\n");
  printf("Running %s with parameters:\n", argv[0]);
  for(int i = 1; i < argc; i++) {
    if(argv[i][0] == '-') printf("\n");
    printf("%s ", argv[i]);
  }
  printf("\nUsing scaling factor of %f", scaling_factor);
  printf("\n");
  if (totime > 0) printf("Timing information will be displayed.\n");
  if (debug) printf("DEBUG MODE IS ENABLED!\n");
  else printf("Debug mode disabled\n");
  printf("------------------------------------------------------------------\n\n");

  // ----------------------------------------------------------------------------
  // Define sw_simulation variables
  // ----------------------------------------------------------------------------

  sw.iteration = 0; // start at zeroeth iteration
  sw.max_entropy_state = 0;
  sw.min_energy_state = 0;
  sw.energy = 0;
  sw.min_important_energy = 0;

  // translation distance should scale with ball radius
  sw.translation_scale *= R;

  // neighbor radius should scale with radius and interaction scale
  sw.neighbor_R = neighbor_scale*R*well_width;

  // Find the upper limit to the maximum number of neighbors a ball could have
  sw.max_neighbors = max_balls_within(2+neighbor_scale*well_width);

  // Energy histogram and weights
  sw.interaction_distance = 2*R*well_width;
  sw.energy_levels = 1; // hard spheres can only have one energy!
  sw.energy_histogram = new long[sw.energy_levels]();
  sw.ln_energy_weights = new double[sw.energy_levels]();

  // Observed and sampled energies
  sw.pessimistic_observation = new bool[sw.energy_levels]();
  sw.pessimistic_samples = new long[sw.energy_levels]();
  sw.optimistic_samples = new long[sw.energy_levels]();

  // Transitions from one energy to another
  sw.biggest_energy_transition = max_balls_within(sw.interaction_distance);
  sw.transitions_table =
    new long[sw.energy_levels*(2*sw.biggest_energy_transition+1)]();

  // Walker histograms
  sw.walkers_up = new long[sw.energy_levels]();


  printf("memory use estimate = %.2g G\n\n",
         8*double(6*sw.energy_levels)/1024/1024/1024);

  sw.balls = new ball[sw.N];

  if(totime < 0) totime = 10*sw.N;

  // Initialize the random number generator with our seed
  random::seed(seed);

  // ----------------------------------------------------------------------------
  // Set up the initial grid of balls
  // ----------------------------------------------------------------------------

  for(int i = 0; i < sw.N; i++) // initialize ball radii
    sw.balls[i].R = R;

    //###########################  pack and save  ####################
  if(pack_and_save_cube==true){
	  INITBOX *box=load_cube(data_dir);
	  if(box!=NULL && box->numAtoms<sw.N) {delete box; box=NULL;}
	  if(box!=NULL){//---------loaded baseAtoms up to max of sw.N
		  printf("loading from baseAtoms.txt\n");
		  for(int count=0;count<(100*box->numAtoms);count++){
			  //mixes indices so the culled atoms are random
			  //atoms are only culled from the end...
			  int n1=floor(random::ran()*(box->numAtoms));
			  int n2=floor(random::ran()*(box->numAtoms));
			  double xTemp=box->list[n1].x;
			  double yTemp=box->list[n1].y;
			  double zTemp=box->list[n1].z;
			  box->list[n1].x=box->list[n2].x;
			  box->list[n1].y=box->list[n2].y;
			  box->list[n1].z=box->list[n2].z;
			  box->list[n2].x=xTemp;
			  box->list[n2].y=yTemp;
			  box->list[n2].z=zTemp;
		  }
		  //box2 is used to cull atoms from the end (if needed)
		  //box2 is simulated to mix the atoms up after culling
		  INITBOX *box2=new INITBOX(box->lx);
		  for(int i=0;i<sw.N;i++) box2->addAtom(box->list[i].x,box->list[i].y,box->list[i].z);
		  delete box;
		  box2->temperature=1000.0;
		  for(int i=0;i<100;i++) box2->simulate(sw.N*100);//mix box
		  sw.len[x] = sw.len[y] = sw.len[z] = box2->lx;
		  for(int i=0;i<sw.N;i++) {
			  sw.balls[i].pos=vector3d(box2->list[i].x,box2->list[i].y,box2->list[i].z);
		  }
		  delete box2;
	  }
	  else{//if no baseAtoms.txt then try to pack the box
		if(ff==0){printf("must initialize using --ff\n"); return 254;}
		printf("building baseAtoms.txt\n");
		const double volume = 4*M_PI/3*R*R*R*sw.N/ff;
		sw.len[x] = sw.len[y] = sw.len[z] = pow(volume, 1.0/3);
		if(pack_cube(sw)==false) {printf("could not fill box\n"); return 254;}
	}//done initializing positions
	  mkdir(data_dir, 0777); // create save directory
	  
	  char *posData = new char[4096];
	  sprintf(posData,"%s/baseAtoms.txt",data_dir);
	  FILE *pos_out = fopen((const char *)posData, "w");
	  sprintf(posData,"L = %g\nN = %i\n",sw.len[x],sw.N);
	  fprintf(pos_out,"%s",posData);
	  for(int i=0;i<sw.N;i++){
		sprintf(posData,"%g %g %g",
				sw.balls[i].pos.x,sw.balls[i].pos.y,sw.balls[i].pos.z);
		fprintf(pos_out,"%s",posData);
		if(i+1<sw.N) fprintf(pos_out,"\n");
	  }
      fclose(pos_out);
      delete[] posData;
      took("Placement");
      return 0;
  }
  //###########################  DONE pack and save  #################
  
  if(force_cube==true){//try to load baseAtoms.txt
	  if(ff==0){printf("must initialize using --ff\n"); return 254;}
	  printf("attempting to load baseAtoms.txt\n");
	  const double volume = 4*M_PI/3*R*R*R*sw.N/ff;
	  sw.len[x] = sw.len[y] = sw.len[z] = pow(volume, 1.0/3);
	  INITBOX *box=load_cube(data_dir);
	  if(box==NULL) {
		  printf("requires initialization on the smallest box\nuse the --pack_and_save --ff -N   flags\n");
		  return 254; }
	  if(box->numAtoms<sw.N){
		  printf("boxAtoms.txt contains less atoms than expected\n");
		  delete box;
		  return 254; }
	  if(box->lx>sw.len[x]){
		  printf("baseAtoms must be in a box smaller than current simulation\n");
		  delete box;
		  return 254; }
	  box->temperature=1000.0;
	  for(int i=0;i<100;i++) box->simulate(sw.N*100);//mix box
      double scaleFactor=sw.len[x]/box->lx;
	  for(int i=0;i<sw.N;i++){
          double x=(box->list[i].x)*scaleFactor;
          double y=(box->list[i].y)*scaleFactor;
          double z=(box->list[i].z)*scaleFactor;
		  sw.balls[i].pos=vector3d(x,y,z);
	  }
	  delete box;
  }
  else {
	  // Balls will be initially placed on a face centered cubic (fcc) grid
	  // Note that the unit cells need not be actually "cubic", but the fcc grid will
      //   be stretched to cell dimensions
	  const double min_cell_width = 2*sqrt(2)*R; // minimum cell width
	  const int spots_per_cell = 4; // spots in each fcc periodic unit cell
	  int cells[3]; // array to contain number of cells in x, y, and z dimensions
	  for(int i = 0; i < 3; i++){
	    cells[i] = int(sw.len[i]/min_cell_width); // max number of cells that will fit
	  }
	
	  // It is usefull to know our cell dimensions
	  double cell_width[3];
	  for(int i = 0; i < 3; i++) cell_width[i] = sw.len[i]/cells[i];
	
	  // If we made our cells to small, return with error
	  for(int i = 0; i < 3; i++){
	    if(cell_width[i] < min_cell_width){
	      printf("Placement cell size too small: (%g,  %g,  %g) coming from (%g, %g, %g)\n",
	             cell_width[0],cell_width[1],cell_width[2],
	             sw.len[0], sw.len[1], sw.len[2]);
	      printf("Minimum allowed placement cell width: %g\n",min_cell_width);
	      printf("Total simulation cell dimensions: (%g,  %g,  %g)\n",
	             sw.len[0],sw.len[1],sw.len[2]);
	      printf("Fixing the chosen ball number, filling fractoin, and relative\n"
	             "  simulation cell dimensions simultaneously does not appear to be possible\n");
	      return 176;
	    }
	  }
	
	  // Define ball positions relative to cell position
	  vector3d* offset = new vector3d[4]();
	  offset[x] = vector3d(0,cell_width[y],cell_width[z])/2;
	  offset[y] = vector3d(cell_width[x],0,cell_width[z])/2;
	  offset[z] = vector3d(cell_width[x],cell_width[y],0)/2;
	
	  // Reserve some spots at random to be vacant
	  const int total_spots = spots_per_cell*cells[x]*cells[y]*cells[z];
	  bool *spot_reserved = new bool[total_spots]();
	  int p; // Index of reserved spot
	  for(int i = 0; i < total_spots-sw.N; i++) {
	    p = floor(random::ran()*total_spots); // Pick a random spot index
	    if(spot_reserved[p] == false) // If it's not already reserved, reserve it
	      spot_reserved[p] = true;
	    else // Otherwise redo this index (look for a new spot)
	      i--;
	  }
	
	  // Place all balls in remaining spots
	  int b = 0;
	  for(int i = 0; i < cells[x]; i++) {
	    for(int j = 0; j < cells[y]; j++) {
	      for(int k = 0; k < cells[z]; k++) {
	        for(int l = 0; l < 4; l++) {
	          if(!spot_reserved[i*(4*cells[z]*cells[y])+j*(4*cells[z])+k*4+l]) {
	            sw.balls[b].pos = vector3d(i*cell_width[x],j*cell_width[y],
	                                       k*cell_width[z]) + offset[l];
	            b++;
	          }
	        }
	      }
	    }
	  }
	  delete[] offset;
	  delete[] spot_reserved;
  }
  took("Placement");

  // ----------------------------------------------------------------------------
  // Print info about the initial configuration for troubleshooting
  // ----------------------------------------------------------------------------

  {
    int most_neighbors =
      initialize_neighbor_tables(sw.balls, sw.N, sw.neighbor_R,
                                 sw.max_neighbors, sw.len, sw.walls);
    if (most_neighbors < 0) {
      fprintf(stderr, "The guess of %i max neighbors was too low. Exiting.\n",
              sw.max_neighbors);
      return 1;
    }
    printf("Neighbor tables initialized.\n");
    printf("The most neighbors is %i, whereas the max allowed is %i.\n",
           most_neighbors, sw.max_neighbors);
  }

  // ----------------------------------------------------------------------------
  // Make sure initial placement is valid
  // ----------------------------------------------------------------------------

  for(int i = 0; i < sw.N; i++) {
    for(int j = 0; j < i; j++) {
      if (overlap(sw.balls[i], sw.balls[j], sw.len, sw.walls)) {
        print_bad(sw.balls, sw.N, sw.len, sw.walls);
        printf("Error in initial placement: balls are overlapping.\n");
        return 253;
      }
    }
  }

  fflush(stdout);

  // ----------------------------------------------------------------------------
  // Initialization of cell
  // ----------------------------------------------------------------------------

  sw.initialize_translation_distance();

  // --------------------------------------------------------------------------
  // end initilization routine.
  // --------------------------------------------------------------------------

  // ----------------------------------------------------------------------------
  // Generate info to put in save files
  // ----------------------------------------------------------------------------

  mkdir(data_dir, 0777); // create save directory

  char *headerinfo = new char[4096];
  sprintf(headerinfo,
          "# version: %s\n"
          "# cell dimensions: (%g, %g, %g)\n"
          "# walls: %i\n"
          "# de_g: %g\n"
          "# seed: %li\n"
          "# N: %i\n"
          "# R: %f\n"
          "# well_width: %g\n"
          "# translation_scale: %g\n"
          "# neighbor_scale: %g\n"
          "# scaling factor: %g\n"
          "# ff: %g\n"
          "# ff_small: %g\n",
          version_identifier(),
          sw.len[0], sw.len[1], sw.len[2], sw.walls, de_g, seed, sw.N, R,
          well_width, sw.translation_scale, neighbor_scale, scaling_factor, ff, ff_small);

  char *g_fname = new char[1024];
  sprintf(g_fname, "%s/%s.dat", data_dir, filename);

  took("Initialization");

  // ----------------------------------------------------------------------------
  // MAIN PROGRAM LOOP
  // ----------------------------------------------------------------------------

  sw.moves.total = 0;
  sw.moves.working = 0;
  sw.iteration = 0;

  // tracking for free energy
  int current_valid_run = 0;
  int current_failed_run = 0;
  int longest_valid_run = 0;
  int longest_failed_run = 0;
  int total_checks_of_small_cell = 0;
  int total_valid_small_checks = 0;
  int total_failed_small_checks = 0;
  int valid_runs = 0;
  int failed_runs = 0;
  double average_valid_run = 0;
  double average_failed_run = 0;

  // Reset energy histogram and sample counts
  for(int i = 0; i < sw.energy_levels; i++){
    sw.energy_histogram[i] = 0;
    sw.pessimistic_samples[i] = 0;
    sw.optimistic_samples[i] = 0;
  }

  do {
    // ---------------------------------------------------------------
    // Move each ball once, add to energy histogram
    // ---------------------------------------------------------------
    for(int i = 0; i < sw.N; i++){
      sw.move_a_ball();
    }

    // just hacking stuff in to see what works
    // do the small bit every 100 n^2 iterations for now
    if (sw.iteration % small_cell_check_period == 0) {
      total_checks_of_small_cell++;

      if(overlap_in_small_cell(sw,  scaling_factor)){
        total_failed_small_checks++;
        
        if (current_failed_run == 0){
          // then valid run just ended so record it
          valid_runs++;
          if(current_valid_run > longest_valid_run)
            longest_valid_run = current_valid_run;
          average_valid_run = average_valid_run + (current_valid_run - average_valid_run)/valid_runs;
          current_valid_run = 0;
        }

        current_failed_run++;

        if(debug){printf("%i - false\n", current_failed_run);}
      }
      else{
        total_valid_small_checks++;

        if (current_valid_run == 0){
          // then failed run just ended so record it
          failed_runs++;
          if(current_failed_run > longest_failed_run)
            longest_failed_run = current_failed_run;
          average_failed_run = average_failed_run + (current_failed_run - average_failed_run)/failed_runs;
          current_failed_run = 0;
        }

        current_valid_run++;

        if(debug){printf("%i - true\n", current_valid_run);}
      }
    }

    // ---------------------------------------------------------------
    // Save to file
    // ---------------------------------------------------------------

    if (time_to_save() || valid_runs == simulation_runs) {
      const clock_t now = clock();
      const double secs_done = double(now)/CLOCKS_PER_SEC;
      const int seconds = int(secs_done) % 60;
      const int minutes = int(secs_done / 60) % 60;
      const int hours = int(secs_done / 3600) % 24;
      const int days = int(secs_done / 86400);
      const long percent_done = 100*valid_runs/simulation_runs;
      printf("Saving data after %i days, %02i:%02i:%02i, %li iterations (%ld%%) "
             "complete.\n", days, hours, minutes, seconds, sw.iteration,
             percent_done);
      fflush(stdout);

      char *countinfo = new char[4096];
      sprintf(countinfo,
              "# iterations: %li\n"
              "# working moves: %li\n"
              "# total moves: %li\n"
              "# acceptance rate: %g\n"
              "# longest failed run: %i\n"
              "# longest valid run: %i\n"
              "# total checks of small cell: %i\n"
              "# total failed small checks: %i\n"
              "# total valid small checks: %i\n"
              "# valid runs: %i\n"
              "# failed runs: %i\n"
              "# average valid run: %g\n"
              "# average failed run: %g\n\n",
              sw.iteration, sw.moves.working, sw.moves.total,
              double(sw.moves.working)/sw.moves.total, longest_failed_run,
              longest_valid_run, total_checks_of_small_cell, total_failed_small_checks,
              total_valid_small_checks, valid_runs, failed_runs, average_valid_run, average_failed_run);

      // Save data
      if(!sw.walls){
        FILE *g_out = fopen((const char *)g_fname, "w");
        fprintf(g_out, "%s", headerinfo);
        fprintf(g_out, "%s", countinfo);
        fclose(g_out);
      }

      delete[] countinfo;
    }
  } while (valid_runs < simulation_runs);
  // ----------------------------------------------------------------------------
  // END OF MAIN PROGRAM LOOP
  // ----------------------------------------------------------------------------

  for (int i=0; i<sw.N; i++) {
    delete[] sw.balls[i].neighbors;
  }
  delete[] sw.balls;
  delete[] sw.ln_energy_weights;
  delete[] sw.energy_histogram;

  delete[] sw.transitions_table;

  delete[] sw.walkers_up;

  delete[] sw.pessimistic_observation;
  delete[] sw.pessimistic_samples;
  delete[] sw.optimistic_samples;

  delete[] headerinfo;
  delete[] g_fname;

  delete[] data_dir;
  delete[] filename;
  delete[] filename_suffix;

  return 0;
}
Beispiel #23
0
  void IpoptInternal::evaluate(){
    if (inputs_check_) checkInputs();
    
    checkInitialBounds();
    

        
    if (gather_stats_) {
      Dictionary iterations;
      iterations["inf_pr"] = std::vector<double>();
      iterations["inf_du"] = std::vector<double>();
      iterations["mu"] = std::vector<double>();
      iterations["d_norm"] = std::vector<double>();
      iterations["regularization_size"] = std::vector<double>();
      iterations["obj"] = std::vector<double>();
      iterations["ls_trials"] = std::vector<int>();
      iterations["alpha_pr"] = std::vector<double>();
      iterations["alpha_du"] = std::vector<double>();
      iterations["obj"] = std::vector<double>();
      stats_["iterations"] = iterations;
    }

    // Reset the counters
    t_eval_f_ = t_eval_grad_f_ = t_eval_g_ = t_eval_jac_g_ = t_eval_h_ = t_callback_fun_ = t_callback_prepare_ = t_mainloop_ = 0;
    
    n_eval_f_ = n_eval_grad_f_ = n_eval_g_ = n_eval_jac_g_ = n_eval_h_ = n_iter_ = 0;
  
    // Get back the smart pointers
    Ipopt::SmartPtr<Ipopt::TNLP> *userclass = static_cast<Ipopt::SmartPtr<Ipopt::TNLP>*>(userclass_);
    Ipopt::SmartPtr<Ipopt::IpoptApplication> *app = static_cast<Ipopt::SmartPtr<Ipopt::IpoptApplication>*>(app_);

    double time1 = clock();
    // Ask Ipopt to solve the problem
    Ipopt::ApplicationReturnStatus status = (*app)->OptimizeTNLP(*userclass);
    double time2 = clock();
    t_mainloop_ = double(time2-time1)/CLOCKS_PER_SEC;
  
#ifdef WITH_SIPOPT
    if(run_sens_ || compute_red_hessian_){
      // Calculate parametric sensitivities
      Ipopt::SmartPtr<Ipopt::SensApplication> *app_sens = static_cast<Ipopt::SmartPtr<Ipopt::SensApplication>*>(app_sens_);
      (*app_sens)->SetIpoptAlgorithmObjects(*app, status);
      (*app_sens)->Run();
    
      // Access the reduced Hessian calculator
#ifdef WITH_CASADI_PATCH
      if(compute_red_hessian_){
        // Get the reduced Hessian
        std::vector<double> red_hess = (*app_sens)->ReducedHessian();
      
        // Get the dimensions
        int N;
        for(N=0; N*N<red_hess.size(); ++N);
        casadi_assert(N*N==red_hess.size());
      
        // Store to statistics
        red_hess_ = DMatrix(Sparsity::dense(N,N),red_hess);
      }
#endif // WITH_CASADI_PATCH
    }
#endif // WITH_SIPOPT
  
    if (hasOption("print_time") && bool(getOption("print_time"))) {
      // Write timings
      cout << "time spent in eval_f: " << t_eval_f_ << " s.";
      if (n_eval_f_>0)
        cout << " (" << n_eval_f_ << " calls, " << (t_eval_f_/n_eval_f_)*1000 << " ms. average)";
      cout << endl;
      cout << "time spent in eval_grad_f: " << t_eval_grad_f_ << " s.";
      if (n_eval_grad_f_>0)
        cout << " (" << n_eval_grad_f_ << " calls, " << (t_eval_grad_f_/n_eval_grad_f_)*1000 << " ms. average)";
      cout << endl;
      cout << "time spent in eval_g: " << t_eval_g_ << " s.";
      if (n_eval_g_>0)
        cout << " (" << n_eval_g_ << " calls, " << (t_eval_g_/n_eval_g_)*1000 << " ms. average)";
      cout << endl;
      cout << "time spent in eval_jac_g: " << t_eval_jac_g_ << " s.";
      if (n_eval_jac_g_>0)
        cout << " (" << n_eval_jac_g_ << " calls, " << (t_eval_jac_g_/n_eval_jac_g_)*1000 << " ms. average)";
      cout << endl;
      cout << "time spent in eval_h: " << t_eval_h_ << " s.";
      if (n_eval_h_>1)
        cout << " (" << n_eval_h_ << " calls, " << (t_eval_h_/n_eval_h_)*1000 << " ms. average)";
      cout << endl;
      cout << "time spent in main loop: " << t_mainloop_ << " s." << endl;
      cout << "time spent in callback function: " << t_callback_fun_ << " s." << endl;
      cout << "time spent in callback preparation: " << t_callback_prepare_ << " s." << endl;
    }

    if (status == Solve_Succeeded)
      stats_["return_status"] = "Solve_Succeeded";
    if (status == Solved_To_Acceptable_Level)
      stats_["return_status"] = "Solved_To_Acceptable_Level";
    if (status == Infeasible_Problem_Detected)
      stats_["return_status"] = "Infeasible_Problem_Detected";
    if (status == Search_Direction_Becomes_Too_Small)
      stats_["return_status"] = "Search_Direction_Becomes_Too_Small";
    if (status == Diverging_Iterates)
      stats_["return_status"] = "Diverging_Iterates";
    if (status == User_Requested_Stop)
      stats_["return_status"] = "User_Requested_Stop";
    if (status == Maximum_Iterations_Exceeded)
      stats_["return_status"] = "Maximum_Iterations_Exceeded";
    if (status == Restoration_Failed)
      stats_["return_status"] = "Restoration_Failed";
    if (status == Error_In_Step_Computation)
      stats_["return_status"] = "Error_In_Step_Computation";
    if (status == Not_Enough_Degrees_Of_Freedom)
      stats_["return_status"] = "Not_Enough_Degrees_Of_Freedom";
    if (status == Invalid_Problem_Definition)
      stats_["return_status"] = "Invalid_Problem_Definition";
    if (status == Invalid_Option)
      stats_["return_status"] = "Invalid_Option";
    if (status == Invalid_Number_Detected)
      stats_["return_status"] = "Invalid_Number_Detected";
    if (status == Unrecoverable_Exception)
      stats_["return_status"] = "Unrecoverable_Exception";
    if (status == NonIpopt_Exception_Thrown)
      stats_["return_status"] = "NonIpopt_Exception_Thrown";
    if (status == Insufficient_Memory)
      stats_["return_status"] = "Insufficient_Memory";
  
    stats_["t_eval_f"] = t_eval_f_;
    stats_["t_eval_grad_f"] = t_eval_grad_f_;
    stats_["t_eval_g"] = t_eval_g_;
    stats_["t_eval_jac_g"] = t_eval_jac_g_;
    stats_["t_eval_h"] = t_eval_h_;
    stats_["t_mainloop"] = t_mainloop_;
    stats_["t_callback_fun"] = t_callback_fun_;
    stats_["t_callback_prepare"] = t_callback_prepare_;
    stats_["n_eval_f"] = n_eval_f_;
    stats_["n_eval_grad_f"] = n_eval_grad_f_;
    stats_["n_eval_g"] = n_eval_g_;
    stats_["n_eval_jac_g"] = n_eval_jac_g_;
    stats_["n_eval_h"] = n_eval_h_;
    
    stats_["iter_count"] = n_iter_-1;
  
  }
/**
 * Generate a height-map.
 *
 * Basically we generate a lot of hills, each hill being centered at a certain
 * point, with a certain radius - being a half sphere.  Hills are combined
 * additively to form a bumpy surface.  The size of each hill varies randomly
 * from 1-hill_size.  We generate 'iterations' hills in total.  The range of
 * heights is normalized to 0-1000.  'island_size' controls whether or not the
 * map should tend toward an island shape, and if so, how large the island
 * should be.  Hills with centers that are more than 'island_size' away from
 * the center of the map will be inverted (i.e. be valleys).  'island_size' as
 * 0 indicates no island.
 */
height_map default_map_generator_job::generate_height_map(size_t width, size_t height, size_t iterations, size_t hill_size, size_t island_size, size_t island_off_center)
{
	height_map res(width, std::vector<int>(height,0));

	size_t center_x = width/2;
	size_t center_y = height/2;

	LOG_NG << "off-centering...\n";

	if(island_off_center != 0) {
		switch(rng_()%4) {
		case 0:
			center_x += island_off_center;
			break;
		case 1:
			center_y += island_off_center;
			break;
		case 2:
			if(center_x < island_off_center) {
				center_x = 0;
			} else {
				center_x -= island_off_center;
			}
			break;
		case 3:
			if(center_y < island_off_center) {
				center_y = 0;
			} else {
				center_y -= island_off_center;
			}
			break;
		}
	}

	for(size_t i = 0; i != iterations; ++i) {

		// (x1,y1) is the location of the hill,
		// and 'radius' is the radius of the hill.
		// We iterate over all points, (x2,y2).
		// The formula for the amount the height is increased by is:
		// radius - sqrt((x2-x1)^2 + (y2-y1)^2) with negative values ignored.
		//
		// Rather than iterate over every single point, we can reduce the points
		// to a rectangle that contains all the positive values for this formula --
		// the rectangle is given by min_x,max_x,min_y,max_y.

		// Is this a negative hill? (i.e. a valley)
		bool is_valley = false;

		int x1 = island_size > 0 ? center_x - island_size + (rng_()%(island_size*2)) : int(rng_()%width);
		int y1 = island_size > 0 ? center_y - island_size + (rng_()%(island_size*2)) : int(rng_()%height);

		// We have to check whether this is actually a valley
		if(island_size != 0) {
			const size_t diffx = std::abs(x1 - int(center_x));
			const size_t diffy = std::abs(y1 - int(center_y));
			const size_t dist = size_t(std::sqrt(double(diffx*diffx + diffy*diffy)));
			is_valley = dist > island_size;
		}

		const int radius = rng_()%hill_size + 1;

		const int min_x = x1 - radius > 0 ? x1 - radius : 0;
		const int max_x = x1 + radius < static_cast<long>(res.size()) ? x1 + radius : res.size();
		const int min_y = y1 - radius > 0 ? y1 - radius : 0;
		const int max_y = y1 + radius < static_cast<long>(res.front().size()) ? y1 + radius : res.front().size();

		for(int x2 = min_x; x2 < max_x; ++x2) {
			for(int y2 = min_y; y2 < max_y; ++y2) {
				const int xdiff = (x2-x1);
				const int ydiff = (y2-y1);

				const int hill_height = radius - int(std::sqrt(double(xdiff*xdiff + ydiff*ydiff)));

				if(hill_height > 0) {
					if(is_valley) {
						if(hill_height > res[x2][y2]) {
							res[x2][y2] = 0;
						} else {
							res[x2][y2] -= hill_height;
						}
					} else {
						res[x2][y2] += hill_height;
					}
				}
			}
		}
	}

	// Find the highest and lowest points on the map for normalization:
	int heighest = 0, lowest = 100000, x;
	for(x = 0; size_t(x) != res.size(); ++x) {
		for(int y = 0; size_t(y) != res[x].size(); ++y) {
			if(res[x][y] > heighest) {
				heighest = res[x][y];
			}

			if(res[x][y] < lowest) {
				lowest = res[x][y];
			}
		}
	}

	// Normalize the heights to the range 0-1000:
	heighest -= lowest;
	for(x = 0; size_t(x) != res.size(); ++x) {
		for(int y = 0; size_t(y) != res[x].size(); ++y) {
			res[x][y] -= lowest;
			res[x][y] *= 1000;
			if(heighest != 0) {
				res[x][y] /= heighest;
			}
		}
	}

	return res;
}
Beispiel #25
0
int _main_(int /*_argc*/, char** /*_argv*/)
{
	uint32_t width = 1280;
	uint32_t height = 720;
	uint32_t debug = BGFX_DEBUG_TEXT;
	uint32_t reset = BGFX_RESET_VSYNC;

	bgfx::init();
	bgfx::reset(width, height, reset);

	// Enable debug text.
	bgfx::setDebug(debug);

	// Set view 0 clear state.
	bgfx::setViewClear(0
		, BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
		, 0x303030ff
		, 1.0f
		, 0
		);

	// Setup root path for binary shaders. Shader binaries are different 
	// for each renderer.
	switch (bgfx::getRendererType() )
	{
	default:
	case bgfx::RendererType::Direct3D9:
		s_shaderPath = "shaders/dx9/";
		break;

	case bgfx::RendererType::Direct3D11:
		s_shaderPath = "shaders/dx11/";
		break;

	case bgfx::RendererType::OpenGL:
		s_shaderPath = "shaders/glsl/";
		break;

	case bgfx::RendererType::OpenGLES:
		s_shaderPath = "shaders/gles/";
		break;
	}

	// Create vertex stream declaration.
	s_PosColorDecl.begin();
	s_PosColorDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
	s_PosColorDecl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
	s_PosColorDecl.end();

	const bgfx::Memory* mem;

	// Create static vertex buffer.
	mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) );
	bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(mem, s_PosColorDecl);

	// Create static index buffer.
	mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) );
	bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(mem);

	// Load vertex shader.
	mem = loadShader("vs_cubes");
	bgfx::ShaderHandle vsh = bgfx::createShader(mem);

	// Load fragment shader.
	mem = loadShader("fs_cubes");
	bgfx::ShaderHandle fsh = bgfx::createShader(mem);

	// Create program from shaders.
	bgfx::ProgramHandle program = bgfx::createProgram(vsh, fsh);

	// We can destroy vertex and fragment shader here since
	// their reference is kept inside bgfx after calling createProgram.
	// Vertex and fragment shader will be destroyed once program is
	// destroyed.
	bgfx::destroyShader(vsh);
	bgfx::destroyShader(fsh);

	float at[3] = { 0.0f, 0.0f, 0.0f };
	float eye[3] = { 0.0f, 0.0f, -35.0f };

	int64_t timeOffset = bx::getHPCounter();

	while (!entry::processEvents(width, height, debug, reset) )
	{
		float view[16];
		float proj[16];
		mtxLookAt(view, eye, at);
		mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f);

		// Set view and projection matrix for view 0.
		bgfx::setViewTransform(0, view, proj);

		// Set view 0 default viewport.
		bgfx::setViewRect(0, 0, 0, width, height);

		// This dummy draw call is here to make sure that view 0 is cleared
		// if no other draw calls are submitted to view 0.
		bgfx::submit(0);

		int64_t now = bx::getHPCounter();
		static int64_t last = now;
		const int64_t frameTime = now - last;
		last = now;
		const double freq = double(bx::getHPFrequency() );
		const double toMs = 1000.0/freq;

		float time = (float)( (now-timeOffset)/double(bx::getHPFrequency() ) );

		// Use debug font to print information about this example.
		bgfx::dbgTextClear();
		bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/01-cube");
		bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Rendering simple static mesh.");
		bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);

		// Submit 11x11 cubes.
		for (uint32_t yy = 0; yy < 11; ++yy)
		{
			for (uint32_t xx = 0; xx < 11; ++xx)
			{
				float mtx[16];
				mtxRotateXY(mtx, time + xx*0.21f, time + yy*0.37f);
				mtx[12] = -15.0f + float(xx)*3.0f;
				mtx[13] = -15.0f + float(yy)*3.0f;
				mtx[14] = 0.0f;

				// Set model matrix for rendering.
				bgfx::setTransform(mtx);

				// Set vertex and fragment shaders.
				bgfx::setProgram(program);

				// Set vertex and index buffer.
				bgfx::setVertexBuffer(vbh);
				bgfx::setIndexBuffer(ibh);

				// Set render states.
				bgfx::setState(BGFX_STATE_DEFAULT);

				// Submit primitive for rendering to view 0.
				bgfx::submit(0);
			}
		}

		// Advance to next frame. Rendering thread will be kicked to 
		// process submitted rendering primitives.
		bgfx::frame();
	}

	// Cleanup.
	bgfx::destroyIndexBuffer(ibh);
	bgfx::destroyVertexBuffer(vbh);
	bgfx::destroyProgram(program);

	// Shutdown bgfx.
	bgfx::shutdown();

	return 0;
}