Esempio n. 1
0
File: rpc.c Progetto: copton/ocram
bool rpc_unmarshall_response(rpc_response_t* response, size_t numberofResponses, uint8_t* buffer, size_t len)
{
    if (numberofResponses == 0) return false;

    size_t offset = 0;

    if (offset + 1 > len) return false;
    response->sequence = buffer[offset++]; 
    
    if (offset + 1 > len) return false;
    response->function = buffer[offset++]; 

    if (0) {
    } else if (response->function == RPC_TELL) {
        if (! rpc_unmarshall_response(response + 1, numberofResponses - 1, buffer + offset, len - offset)) {
            return false;
        }
        response->data.tell.response = response + 1;
    } else if (response->function == RPC_READ_SLOW_SENSOR) {
        if (rcopy(&response->data.read_slow_sensor.value, sizeof(response->data.read_slow_sensor.value), buffer, len, &offset)) return false;
    } else if (response->function == RPC_READ_FAST_SENSOR) {
        if (rcopy(&response->data.read_fast_sensor.value, sizeof(response->data.read_fast_sensor.value), buffer, len, &offset)) return false;
    } else {
        return false;
    }

    return true;
}
Esempio n. 2
0
void func_rvec_set(func_t *f, int i, func_t *g)
{
  func_t *a=NULL;
  if(f==NULL || func_ptype(f)!=FUNC_P_RVEC || f->p.rvec==NULL || i<0 || i>=f->p.rvec->n){ FUNC_ERROR_ARG2("func_rvec_set",f,g); }
  a=func_evalf(FR(g));
  if     (func_is_real(a))                          { rcopy(func_rvec_at(f,i),func_real_p(a)); }
  else if(func_is(a,"rvec") && func_rvec_size(a)==1){ rcopy(func_rvec_at(f,i),func_rvec_at(a,0)); }
  else{ FUNC_ERROR_ARG2("func_rvec_set",f,g); } 
  a=func_del(a);
}
Esempio n. 3
0
void btree::rcopy(btnode* &pn, const btnode * const s)
{
    if(s != NULL)
    {
        pn = new btnode( s->data );
        assert(pn != NULL);
        rcopy(pn->ltree, s->ltree);
        rcopy(pn->rtree, s->rtree);
    }
}
Esempio n. 4
0
/**
 @brief QEより行列Aを生成
*/
void riep_dhToda_QE_to_A(int m, int M, rmulti **A, int LDA, rmulti **Q, int LDQ, rmulti **E, int debug)
{
    // init
    int k=0,n=0,l=0,LDR=0,prec=0;
    rmulti **R=NULL;

    // precision
    prec=rmat_get_prec_max(m,m,A,LDA);

    //allocate
    LDR=m;
    R=rmat_allocate_prec(LDR,m,prec);

    // set A=L
    for(n=0; n<m; n++) {
        for(k=0; k<m; k++) {
            if     (n==k)    {
                rset_one(MAT(A,n,k,LDA));    // A[n][k]=1
            }
            else if((n-k)==1) {
                rcopy(MAT(A,n,k,LDA),E[k]);    // A[n][k]=E[k][0]
            }
            else             {
                rset_zero(MAT(A,n,k,LDA));    // A[n][k]=0
            }
        }
    }
    // set A=A*R
    for(l=M-1; l>=0; l--) {
        for(n=0; n<m; n++) {
            for(k=0; k<m; k++) {
                if     ((k-n)==1) {
                    rset_one(MAT(R,n,k,LDR));    // R[n][k]=1
                }
                else if(n==k)    {
                    rcopy(MAT(R,n,k,LDR),MAT(Q,k,l,LDQ));    // R[n][k]=Q[k][l]
                }
                else             {
                    rset_zero(MAT(R,n,k,LDR));    // R[n][k]=0
                }
            }
        }
        rmat_prod(m,m,m,A,LDA,A,LDA,R,LDR); // A=A*R
    }
    // debug
    if(debug>0) {

    }
    //done
    R=rmat_free(LDR,m,R);

}
Esempio n. 5
0
int main(int argc, char *argv[]) {
    // check arguments
    if (argc != NUM_ARGS) {
        std::cerr << "usage: " << argv[0] << "from-remote-file to-local-file "
                     "buffer-size error-percent window-size remote-machine "
                     "remote-port" << std::endl;
        return EXIT_FAILURE;
    }
    
    // Initialize errors
    sendErr_init(atof(argv[ARG_PERR]), DROP_ON, FLIP_ON, DEBUG_ON, RSEED_OFF);
    
    // Create client
    try {
        Client rcopy(argv[ARG_FROM], argv[ARG_TO], atoi(argv[ARG_BUFSZ]),
                     atof(argv[ARG_PERR]),atoi(argv[ARG_WINSZ]),
                     argv[ARG_REMNAME], argv[ARG_REMPORT]);
        rcopy.Run();
    } catch (Exception &e) {
        std::cerr << e.What() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
Esempio n. 6
0
btree::btree(const btree &src)
{
    entry = NULL;
    next = NULL;
    toggle = false;
    rval = 0;
    rcopy(entry, src.entry); 
}
Esempio n. 7
0
File: pmov.c Progetto: 8l/qbe
static void
replay()
{
	RMap mend;

	re = 1;
	bsinit_(mend.b, Tmp0+NIReg);
	rcopy(&mend, &mbeg);
	dopm(&dummyb, ip-1, &mend);
}
Esempio n. 8
0
void Frame::rectangle (const Rectangle& rect)
{
    Rectangle rcopy(rect);
    rcopy.x1 += originX;
    rcopy.x2 += originX;
    rcopy.y1 += originY;
    rcopy.y2 += originY;
    fixFillColor(&rcopy);
    fixStrokeStyle(&rcopy);
    display->rectangle(rcopy);
}
Esempio n. 9
0
File: rpc.c Progetto: copton/ocram
bool rpc_unmarshall_call(rpc_call_t* call, size_t numberofCalls, uint8_t* buffer, size_t len)
{
    if (numberofCalls == 0) {return false;}

    size_t offset = 0;

    if (offset + 1 > len) {return false;}
    call->sequence = buffer[offset++]; 

    if (offset + 1 > len) {return false;}
    call->function = buffer[offset++]; 

    if (0) {
    } else if (call->function == RPC_TELL) {
        if (rcopy(call->data.tell.peer.u8, sizeof(call->data.tell.peer.u8), buffer, len, &offset)) {
            return false;
        }

        if (! rpc_unmarshall_call(call + 1, numberofCalls - 1, buffer + offset, len - offset)) {
            return false;
        }
        call->data.tell.call = call + 1;
    } else if (call->function == RPC_READ_SLOW_SENSOR) {
        if (rcopy(&call->data.read_slow_sensor.sensor, sizeof(call->data.read_slow_sensor.sensor), buffer, len, &offset)) {
            return false;
        }
    } else if (call->function == RPC_READ_FAST_SENSOR) {
        if (rcopy(&call->data.read_fast_sensor.sensor, sizeof(call->data.read_fast_sensor.sensor), buffer, len, &offset)) {
            return false;
        }
    } else {
        return false;
    }

    return true;
}
Esempio n. 10
0
Arc *
newarc(Node *n, Rule *r, char *stem, Resub *match)
{
	Arc *a;

	a = (Arc *)Malloc(sizeof(Arc));
	a->n = n;
	a->r = r;
	a->stem = strdup(stem);
	rcopy(a->match, match, NREGEXP);
	a->next = 0;
	a->flag = 0;
	a->prog = r->prog;
	return(a);
}
void rsort(int arr[], int len) 
{
  queue *qs[10];
  for (int i = 0; i < 10; i++) qs[i] = QueueNew();

  for (int i = 0; i < 3 ; i++) { // 3 digit mods
    for (int j = 0; j < len; j++) { // array index
      int tmp = arr[j];
      for (int k = 0; k < i; k++) tmp /= 10; // get current digit
      int index = (tmp % 10); // bucket
      QueueAdd(qs[index], arr[j]);
    }
    rcopy(qs, 10, arr, len); // dump back to array
  }
    
  for (int i = 0; i < 10; i++) QueueFree(qs[i]);
}
Esempio n. 12
0
/**
 @brief ハウスホルダー・ベクトルへの変換.
 @details h[0]=0; ...; h[k-1]=0; h[k]=-s*xi; h[k+1]=x[k+1]; ...; h[n-1]=x[n-1];
 @param[in]  h 初期化済みのベクトル.サイズはn.
 @param[in]  x 初期化済みのベクトル.サイズはn.
 @param[in]  n ベクトルのサイズ.
 @param[in]  k 第k要素が基準.
 @param[out] h ハウスホルダー・ベクトル.
 */
void rhouseholder_vec(int n, int k, rmulti **h, rmulti *alpha, rmulti **x)
{
  int p0,p1,prec;
  rmulti *eta=NULL,*zeta=NULL,*xi=NULL,*axk=NULL;
  // allocate
  p0=rget_prec(alpha);
  p1=rvec_get_prec_max(n,h);
  prec=MAX2(p0,p1);
  eta=rallocate_prec(prec);
  zeta=rallocate_prec(prec);
  xi=rallocate_prec(prec);
  axk=rallocate_prec(prec);
  //----------- norm
  rvec_sum_pow2(xi,n-k-1,&x[k+1]);    // xi=sum(abs(x((k+1):end)).^2);
  rmul(axk,x[k],x[k]);                // axk=|x[k]|^2
  radd(eta,axk,xi);                   // eta=|x[k]|^2+...
  rsqrt(axk,axk);                     // axk=|x[k]|
  rsqrt(eta,eta);                     // eta=sqrt(|x[k]|^2+...)
  if(req_d(eta,0)){rsub(xi,eta,axk);} // xi=eta-|x(k)|
  else{                               // xi=xi/(|x(k)|+eta)
    radd(zeta,axk,eta);
    rdiv(xi,xi,zeta);
  }
  //----------- h
  rvec_set_zeros(k,h);
  rvec_copy(n-k-1,&h[k+1],&x[k+1]);     // h((k+1):end)=x((k+1):end);
  if(ris_zero(x[k])){
    rcopy(h[k],xi); rneg(h[k],h[k]);    // h[k]=-xi
  }else{
    rdiv(zeta,xi,axk); rneg(zeta,zeta); // zeta=-xi/axk;
    rmul(h[k],x[k],zeta);               // h[k]=zeta*x[k];
  }
  //----------- alpha
  if(req_d(xi,0) || req_d(eta,0)){
    rset_d(alpha,0);
  }else{
    rmul(alpha,xi,eta);                 // alpha=1/(xi*eta)
    rinv(alpha,alpha);
  }
  // free
  eta=rfree(eta);
  zeta=rfree(zeta);
  xi=rfree(xi);
  axk=rfree(axk);
}
Esempio n. 13
0
/*************************************************************************
* This function is the entry point of the initial partitioning algorithm.
* This algorithm assembles the graph to all the processors and preceed
* serially.
**************************************************************************/
idx_t Mc_Diffusion(ctrl_t *ctrl, graph_t *graph, idx_t *vtxdist, idx_t *where, 
          idx_t *home, idx_t npasses)
{
  idx_t h, i, j;
  idx_t nvtxs, nedges, ncon, pass, iter, domain, processor;
  idx_t nparts, mype, npes, nlinks, me, you, wsize;
  idx_t nvisited, nswaps = -1, tnswaps, done, alldone = -1;
  idx_t *rowptr, *colind, *diff_where, *sr_where, *ehome, *map, *rmap;
  idx_t *pack, *unpack, *match, *proc2sub, *sub2proc;
  idx_t *visited, *gvisited;
  real_t *transfer, *npwgts, maxdiff, minflow, maxflow;
  real_t lbavg, oldlbavg, ubavg, *lbvec;
  real_t *diff_flows, *sr_flows;
  real_t diff_lbavg, sr_lbavg, diff_cost, sr_cost;
  idx_t *rbuffer, *sbuffer; 
  idx_t *rcount, *rdispl;
  real_t *solution, *load, *workspace;
  matrix_t matrix;
  graph_t *egraph;

  if (graph->ncon > 3)
    return 0;

  WCOREPUSH;

  nvtxs  = graph->nvtxs;
  nedges = graph->nedges;
  ncon   = graph->ncon;

  nparts = ctrl->nparts;
  mype   = ctrl->mype;
  npes   = ctrl->npes;
  ubavg  = ravg(ncon, ctrl->ubvec);

  /* initialize variables and allocate memory */
  lbvec      = rwspacemalloc(ctrl, ncon);
  diff_flows = rwspacemalloc(ctrl, ncon);
  sr_flows   = rwspacemalloc(ctrl, ncon);

  load                       = rwspacemalloc(ctrl, nparts);
  solution                   = rwspacemalloc(ctrl, nparts);
  npwgts = graph->gnpwgts    = rwspacemalloc(ctrl, ncon*nparts);
  matrix.values              = rwspacemalloc(ctrl, nedges);
  transfer = matrix.transfer = rwspacemalloc(ctrl, ncon*nedges);

  proc2sub               = iwspacemalloc(ctrl, gk_max(nparts, npes*2));
  sub2proc               = iwspacemalloc(ctrl, nparts);
  match                  = iwspacemalloc(ctrl, nparts);
  rowptr = matrix.rowptr = iwspacemalloc(ctrl, nparts+1);
  colind = matrix.colind = iwspacemalloc(ctrl, nedges);

  rcount = iwspacemalloc(ctrl, npes);
  rdispl = iwspacemalloc(ctrl, npes+1);

  pack       = iwspacemalloc(ctrl, nvtxs);
  unpack     = iwspacemalloc(ctrl, nvtxs);
  rbuffer    = iwspacemalloc(ctrl, nvtxs);
  sbuffer    = iwspacemalloc(ctrl, nvtxs);
  map        = iwspacemalloc(ctrl, nvtxs);
  rmap       = iwspacemalloc(ctrl, nvtxs);
  diff_where = iwspacemalloc(ctrl, nvtxs);
  ehome      = iwspacemalloc(ctrl, nvtxs);


  wsize = gk_max(sizeof(real_t)*nparts*6, sizeof(idx_t)*(nvtxs+nparts*2+1));
  workspace = (real_t *)gk_malloc(wsize, "Mc_Diffusion: workspace");

  graph->ckrinfo = (ckrinfo_t *)gk_malloc(nvtxs*sizeof(ckrinfo_t), "Mc_Diffusion: rinfo");


  /* construct subdomain connectivity graph */
  matrix.nrows = nparts;
  SetUpConnectGraph(graph, &matrix, (idx_t *)workspace);
  nlinks = (matrix.nnzs-nparts) / 2;

  visited  = iwspacemalloc(ctrl, matrix.nnzs);
  gvisited = iwspacemalloc(ctrl, matrix.nnzs);

  for (pass=0; pass<npasses; pass++) {
    rset(matrix.nnzs*ncon, 0.0, transfer);
    iset(matrix.nnzs, 0, gvisited);
    iset(matrix.nnzs, 0, visited);
    iter = nvisited = 0;

    /* compute ncon flow solutions */
    for (h=0; h<ncon; h++) {
      rset(nparts, 0.0, solution);
      ComputeLoad(graph, nparts, load, ctrl->tpwgts, h);

      lbvec[h] = (rmax(nparts, load)+1.0/nparts) * (real_t)nparts;

      ConjGrad2(&matrix, load, solution, 0.001, workspace);
      ComputeTransferVector(ncon, &matrix, solution, transfer, h);
    }

    oldlbavg = ravg(ncon, lbvec);
    tnswaps = 0;
    maxdiff = 0.0;
    for (i=0; i<nparts; i++) {
      for (j=rowptr[i]; j<rowptr[i+1]; j++) {
        maxflow = rmax(ncon, transfer+j*ncon);
        minflow = rmin(ncon, transfer+j*ncon);
        maxdiff = (maxflow - minflow > maxdiff) ? maxflow - minflow : maxdiff;
      }
    }

    while (nvisited < nlinks) {
      /* compute independent sets of subdomains */
      iset(gk_max(nparts, npes*2), UNMATCHED, proc2sub);
      CSR_Match_SHEM(&matrix, match, proc2sub, gvisited, ncon);

      /* set up the packing arrays */
      iset(nparts, UNMATCHED, sub2proc);
      for (i=0; i<npes*2; i++) {
        if (proc2sub[i] == UNMATCHED)
          break;

        sub2proc[proc2sub[i]] = i/2;
      }

      iset(npes, 0, rcount);
      for (i=0; i<nvtxs; i++) {
        domain = where[i];
        processor = sub2proc[domain];
        if (processor != UNMATCHED) 
          rcount[processor]++;
      }

      rdispl[0] = 0;
      for (i=1; i<npes+1; i++)
        rdispl[i] = rdispl[i-1] + rcount[i-1];

      iset(nvtxs, UNMATCHED, unpack);
      for (i=0; i<nvtxs; i++) {
        domain = where[i];
        processor = sub2proc[domain];
        if (processor != UNMATCHED) 
          unpack[rdispl[processor]++] = i;
      }

      SHIFTCSR(i, npes, rdispl);

      iset(nvtxs, UNMATCHED, pack);
      for (i=0; i<rdispl[npes]; i++) {
        ASSERT(unpack[i] != UNMATCHED);
        domain = where[unpack[i]];
        processor = sub2proc[domain];
        if (processor != UNMATCHED) 
          pack[unpack[i]] = i;
      }

      /* Compute the flows */
      if (proc2sub[mype*2] != UNMATCHED) {
        me  = proc2sub[2*mype];
        you = proc2sub[2*mype+1];
        ASSERT(me != you);

        for (j=rowptr[me]; j<rowptr[me+1]; j++) {
          if (colind[j] == you) {
            visited[j] = 1;
            rcopy(ncon, transfer+j*ncon, diff_flows);
            break;
          }
        }

        for (j=rowptr[you]; j<rowptr[you+1]; j++) {
          if (colind[j] == me) {
            visited[j] = 1;
            for (h=0; h<ncon; h++) {
              if (transfer[j*ncon+h] > 0.0)
                diff_flows[h] = -1.0 * transfer[j*ncon+h];
            }
            break;
          }
        } 

        nswaps = 1;
        rcopy(ncon, diff_flows, sr_flows);

        iset(nvtxs, 0, sbuffer);
        for (i=0; i<nvtxs; i++) {
          if (where[i] == me || where[i] == you)
            sbuffer[i] = 1;
        }

        egraph = ExtractGraph(ctrl, graph, sbuffer, map, rmap);

        if (egraph != NULL) {
          icopy(egraph->nvtxs, egraph->where, diff_where);
          for (j=0; j<egraph->nvtxs; j++)
            ehome[j] = home[map[j]];
 
          RedoMyLink(ctrl, egraph, ehome, me, you, sr_flows, &sr_cost, &sr_lbavg);

          if (ncon <= 4) {
            sr_where      = egraph->where;
            egraph->where = diff_where;

            nswaps = BalanceMyLink(ctrl, egraph, ehome, me, you, diff_flows, maxdiff, 
                         &diff_cost, &diff_lbavg, 1.0/(real_t)nvtxs);

            if ((sr_lbavg < diff_lbavg &&
                (diff_lbavg >= ubavg-1.0 || sr_cost == diff_cost)) ||
                (sr_lbavg < ubavg-1.0 && sr_cost < diff_cost)) {
              for (i=0; i<egraph->nvtxs; i++)
                where[map[i]] = sr_where[i];
            }
            else {
              for (i=0; i<egraph->nvtxs; i++)
                where[map[i]] = diff_where[i];
            }
          }
          else {
            for (i=0; i<egraph->nvtxs; i++)
              where[map[i]] = egraph->where[i];
          }

          gk_free((void **)&egraph->xadj, &egraph->nvwgt, &egraph->adjncy, &egraph, LTERM);
        }

        /* Pack the flow data */
        iset(nvtxs, UNMATCHED, sbuffer);
        for (i=0; i<nvtxs; i++) {
          domain = where[i];
          if (domain == you || domain == me) 
            sbuffer[pack[i]] = where[i];
        }
      }

      /* Broadcast the flow data */
      gkMPI_Allgatherv((void *)&sbuffer[rdispl[mype]], rcount[mype], IDX_T, 
          (void *)rbuffer, rcount, rdispl, IDX_T, ctrl->comm);

      /* Unpack the flow data */
      for (i=0; i<rdispl[npes]; i++) {
        if (rbuffer[i] != UNMATCHED) 
          where[unpack[i]] = rbuffer[i];
      }


      /* Do other stuff */
      gkMPI_Allreduce((void *)visited, (void *)gvisited, matrix.nnzs,
          IDX_T, MPI_MAX, ctrl->comm);
      nvisited = isum(matrix.nnzs, gvisited, 1)/2;
      tnswaps += GlobalSESum(ctrl, nswaps);

      if (iter++ == NGD_PASSES)
        break;
    }

    /* perform serial refinement */
    Mc_ComputeSerialPartitionParams(ctrl, graph, nparts);
    Mc_SerialKWayAdaptRefine(ctrl, graph, nparts, home, ctrl->ubvec, 10);

    /* check for early breakout */
    for (h=0; h<ncon; h++) {
      lbvec[h] = (real_t)(nparts) *
        npwgts[rargmax_strd(nparts,npwgts+h,ncon)*ncon+h];
    }
    lbavg = ravg(ncon, lbvec);

    done = 0;
    if (tnswaps == 0 || lbavg >= oldlbavg || lbavg <= ubavg + 0.035)
      done = 1;

    alldone = GlobalSEMax(ctrl, done);
    if (alldone == 1)
      break;
  }

  /* ensure that all subdomains have at least one vertex */
/*
  iset(nparts, 0, match);
  for (i=0; i<nvtxs; i++)
    match[where[i]]++;

  done = 0;
  while (done == 0) {
    done = 1;

    me = iargmin(nparts, match);  
    if (match[me] == 0) {
      if (ctrl->mype == PE) printf("WARNING: empty subdomain %"PRIDX" in Mc_Diffusion\n", me);
      you = iargmax(nparts, match);  
      for (i=0; i<nvtxs; i++) {
        if (where[i] == you) {
          where[i] = me;
          match[you]--;
          match[me]++;
          done = 0;
          break;
        }
      }
    }
  }
*/
 
  /* now free memory and return */
  gk_free((void **)&workspace, (void **)&graph->ckrinfo, LTERM);
  graph->gnpwgts = NULL;
  graph->ckrinfo = NULL;

  WCOREPOP;

  return 0;
}
Esempio n. 14
0
ctrl_t *SetupCtrl(moptype_et optype, idx_t *options, idx_t ncon, idx_t nparts, 
            real_t *tpwgts, real_t *ubvec)
{
  idx_t i, j;
  ctrl_t *ctrl;

  ctrl = (ctrl_t *)gk_malloc(sizeof(ctrl_t), "SetupCtrl: ctrl");
  
  memset((void *)ctrl, 0, sizeof(ctrl_t));

  switch (optype) {
    case METIS_OP_PMETIS:
      ctrl->objtype   = GETOPTION(options, METIS_OPTION_OBJTYPE, METIS_OBJTYPE_CUT);
      ctrl->ctype     = GETOPTION(options, METIS_OPTION_CTYPE,   METIS_CTYPE_SHEM);
      ctrl->rtype     = METIS_RTYPE_FM;
      ctrl->ncuts     = GETOPTION(options, METIS_OPTION_NCUTS,   1);
      ctrl->niter     = GETOPTION(options, METIS_OPTION_NITER,   10);
      ctrl->seed      = GETOPTION(options, METIS_OPTION_SEED,    -1);
      ctrl->dbglvl    = GETOPTION(options, METIS_OPTION_DBGLVL,  0);

      if (ncon == 1) {
        ctrl->iptype    = GETOPTION(options, METIS_OPTION_IPTYPE,  METIS_IPTYPE_GROW);
        ctrl->ufactor   = GETOPTION(options, METIS_OPTION_UFACTOR, PMETIS_DEFAULT_UFACTOR);
        ctrl->CoarsenTo = 20;
      }
      else {
        ctrl->iptype    = GETOPTION(options, METIS_OPTION_IPTYPE,  METIS_IPTYPE_RANDOM);
        ctrl->ufactor   = GETOPTION(options, METIS_OPTION_UFACTOR, MCPMETIS_DEFAULT_UFACTOR);
        ctrl->CoarsenTo = 100;
      }

      break;


    case METIS_OP_KMETIS:
      ctrl->objtype  = GETOPTION(options, METIS_OPTION_OBJTYPE, METIS_OBJTYPE_CUT);
      ctrl->ctype    = GETOPTION(options, METIS_OPTION_CTYPE,   METIS_CTYPE_SHEM);
      ctrl->iptype   = METIS_IPTYPE_METISRB;
      ctrl->rtype    = METIS_RTYPE_GREEDY;
      ctrl->ncuts    = GETOPTION(options, METIS_OPTION_NCUTS,   1);
      ctrl->niter    = GETOPTION(options, METIS_OPTION_NITER,   10);
      ctrl->ufactor  = GETOPTION(options, METIS_OPTION_UFACTOR, KMETIS_DEFAULT_UFACTOR);
      ctrl->minconn  = GETOPTION(options, METIS_OPTION_MINCONN, 0);
      ctrl->contig   = GETOPTION(options, METIS_OPTION_CONTIG,  0);
      ctrl->seed     = GETOPTION(options, METIS_OPTION_SEED,    -1);
      ctrl->dbglvl   = GETOPTION(options, METIS_OPTION_DBGLVL,  0);
      break;


    case METIS_OP_OMETIS:
      ctrl->objtype  = GETOPTION(options, METIS_OPTION_OBJTYPE,  METIS_OBJTYPE_NODE);
      ctrl->ctype    = GETOPTION(options, METIS_OPTION_CTYPE,    METIS_CTYPE_SHEM);
      ctrl->rtype    = GETOPTION(options, METIS_OPTION_RTYPE,    METIS_RTYPE_SEP1SIDED);
      ctrl->iptype   = GETOPTION(options, METIS_OPTION_IPTYPE,   METIS_IPTYPE_EDGE);
      ctrl->nseps    = GETOPTION(options, METIS_OPTION_NSEPS,    1);
      ctrl->niter    = GETOPTION(options, METIS_OPTION_NITER,    10);
      ctrl->ufactor  = GETOPTION(options, METIS_OPTION_UFACTOR,  OMETIS_DEFAULT_UFACTOR);
      ctrl->compress = GETOPTION(options, METIS_OPTION_COMPRESS, 1);
      ctrl->ccorder  = GETOPTION(options, METIS_OPTION_CCORDER,  0);
      ctrl->seed     = GETOPTION(options, METIS_OPTION_SEED,     -1);
      ctrl->dbglvl   = GETOPTION(options, METIS_OPTION_DBGLVL,   0);
      ctrl->pfactor  = 0.1*GETOPTION(options, METIS_OPTION_PFACTOR,  0);

      ctrl->CoarsenTo = 100;
      break;

    default:
      gk_errexit(SIGERR, "Unknown optype of %d\n", optype);
  }

  ctrl->numflag  = GETOPTION(options, METIS_OPTION_NUMBERING, 0);
  ctrl->optype   = optype;
  ctrl->ncon     = ncon;
  ctrl->nparts   = nparts;
  ctrl->maxvwgt  = ismalloc(ncon, 0, "SetupCtrl: maxvwgt");


  /* setup the target partition weights */
  if (ctrl->optype != METIS_OP_OMETIS) {
    ctrl->tpwgts = rmalloc(nparts*ncon, "SetupCtrl: ctrl->tpwgts");
    if (tpwgts) {
      rcopy(nparts*ncon, tpwgts, ctrl->tpwgts);
    }
    else {
      for (i=0; i<nparts; i++) {
        for (j=0; j<ncon; j++)
          ctrl->tpwgts[i*ncon+j] = 1.0/nparts;
      }
    }
  }
  else {  /* METIS_OP_OMETIS */
    /* this is required to allow the pijbm to be defined properly for
       the edge-based refinement during initial partitioning */
    ctrl->tpwgts    = rsmalloc(2, .5,  "SetupCtrl: ctrl->tpwgts");
  }


  /* setup the ubfactors */
  ctrl->ubfactors = rsmalloc(ctrl->ncon, I2RUBFACTOR(ctrl->ufactor), "SetupCtrl: ubfactors");
  if (ubvec)
    rcopy(ctrl->ncon, ubvec, ctrl->ubfactors);
  for (i=0; i<ctrl->ncon; i++)
    ctrl->ubfactors[i] += 0.0000499;

  /* Allocate memory for balance multipliers. 
     Note that for PMETIS/OMETIS routines the memory allocated is more 
     than required as balance multipliers for 2 parts is sufficient. */
  ctrl->pijbm = rmalloc(nparts*ncon, "SetupCtrl: ctrl->pijbm");

  InitRandom(ctrl->seed);

  IFSET(ctrl->dbglvl, METIS_DBG_INFO, PrintCtrl(ctrl));

  if (!CheckParams(ctrl)) {
    FreeCtrl(&ctrl);
    return NULL;
  }
  else {
    return ctrl;
  }
}
Esempio n. 15
0
void riep_dhToda_TN(int m, int M, rmulti **A, int LDA, rmulti **Q, int LDQ, rmulti **E, rmulti **lambda, rmulti **c, int debug)
{
    int prec=0,k=0,n=0,f_size=0,n_size=0,*Q0_size=NULL,*E0_size=NULL,LDQ1;
    rmulti *a=NULL,**f=NULL,***Q0=NULL,***E0=NULL,**sigma=NULL,**Q1=NULL,**E1=NULL;

    // init
    n_size=(M+1)*(m-1)+2*M;
    // precision
    prec=rmat_get_prec_max(m,m,A,LDA);

    // allocate
    if(Q==NULL) {
        LDQ1=m;
        Q1=rmat_allocate_prec(m,M,prec);
    }
    else {
        LDQ1=LDQ;
        Q1=Q;
    }
    if(E==NULL) {
        E1=rvec_allocate_prec(m,prec);
    }
    else {
        E1=E;
    }
    sigma=rvec_allocate_prec(m,prec);
    a=rallocate_prec(prec);
    Q0_size=ivec_allocate(m);
    Q0=malloc(m*sizeof(rmulti**));
    for(k=0; k<m; k++) {
        Q0_size[k]=n_size-k*(M+1);
        Q0[k]=rvec_allocate_prec(Q0_size[k],prec);
    }
    E0_size=ivec_allocate(m);
    E0=malloc(m*sizeof(rmulti**));
    for(k=0; k<m; k++) {
        E0_size[k]=n_size-(k+1)*(M+1)+1;
        E0[k]=rvec_allocate_prec(E0_size[k],prec);
    }
    f_size=Q0_size[0]+1;
    f=rvec_allocate_prec(f_size,prec);

    // generate sigma[n]
    rinv_d(a,M);
    rvec_pow_r(m,sigma,lambda,a);
    // generate f[n]
    for(n=0; n<f_size; n++) {
        rset_d(f[n],0);
        for(k=0; k<m; k++) {
            rpow_si(a,sigma[k],n); // a=(sigma[i])^n
            radd_mul(f[n],c[k],a); // f[i]=f[i]+c[i]*(sigma[i])^n
        }
    }
    // Q[n][0]=f[n+1]/f[n]
    for(n=0; n<Q0_size[0]; n++) {
        if(n+1<f_size) {
            rdiv(Q0[0][n],f[n+1],f[n]);
        }
        else          {
            rset_nan(Q0[0][n]);
        }
    }
    // E[0][n]=Q[0][n+M]-Q[0][n];
    k=0;
    for(n=0; n<E0_size[k]; n++) {
        if(n+M<Q0_size[k] && n<Q0_size[k]) {
            rsub(E0[k][n],Q0[k][n+M],Q0[k][n]);
        }
        else                              {
            rset_nan(E0[k][n]);
        }
    }
    // loop for QE-table
    for(k=1; k<m; k++) {
        // Q[k][n]=(E[k-1][n+1]*Q[k-1][n+M])/E[k-1][n];
        for(n=0; n<Q0_size[k]; n++) {
            rdiv(a,E0[k-1][n+1],E0[k-1][n]);
            rmul(Q0[k][n],a,Q0[k-1][n+M]);
        }
        // E[k][n]=Q[k][n+M]-Q[k][n]+E[k-1][n+1]
        for(n=0; n<E0_size[k]; n++) {
            rsub(a,Q0[k][n+M],Q0[k][n]);
            radd(E0[k][n],a,E0[k-1][n+1]);
        }
    }

    // debug
    if(debug>0) {
        printf("Q=\n");
        for(n=0; n<n_size; n++) {
            for(k=0; k<m; k++) {
                if(n<Q0_size[k]) {
                    mpfr_printf("%.3Re ",Q0[k][n]);
                }
            }
            printf("\n");
        }
        printf("E=\n");
        for(n=0; n<n_size; n++) {
            for(k=0; k<m; k++) {
                if(n<E0_size[k]) {
                    mpfr_printf("%.3Re ",E0[k][n]);
                }
            }
            printf("\n");
        }
    }

    // generate vector E
    for(k=0; k<m; k++) {
        rcopy(E1[k],E0[k][0]);
    }

    // generate matrix Q
    for(n=0; n<M; n++) {
        for(k=0; k<m; k++) {
            rcopy(MAT(Q1,k,n,LDQ1),Q0[k][n]);
        }
    }


    // genrate matrix A
    if(A!=NULL) {
        riep_dhToda_QE_to_A(m,M,A,LDA,Q1,LDQ1,E1,debug);
    }

    // done
    if(Q==NULL) {
        Q1=rmat_free(LDQ1,M,Q1);
    }
    else {
        Q1=NULL;
    }
    if(E==NULL) {
        E1=rvec_free(m,E1);
    }
    else {
        E1=NULL;
    }
    a=rfree(a);
    f=rvec_free(f_size,f);
    sigma=rvec_free(m,sigma);
    for(k=0; k<m; k++) {
        Q0[k]=rvec_free(Q0_size[k],Q0[k]);
    }
    free(Q0);
    Q0=NULL;
    for(k=0; k<m; k++) {
        E0[k]=rvec_free(E0_size[k],E0[k]);
    }
    free(E0);
    E0=NULL;
    Q0_size=ivec_free(Q0_size);
    E0_size=ivec_free(E0_size);
    return;
}
Esempio n. 16
0
const btree &btree::operator =(const btree &src)
{
    release();
    rcopy(entry, src.entry);
    return *this;
}
Esempio n. 17
0
void overwriteProc(XtPointer fsel, int conf)
{
 SelFileNamesRec *fnames = (SelFileNamesRec *) fsel;
 char to[MAXPATHLEN], from[MAXPATHLEN];
 String errstr;
 struct stat tolstats;
 size_t len;
 int devto, devfrom, deverr = -1, res;

 switch (conf)
 {
     case CANCEL:	fnames->first = fnames->n_sel; break;
     case ALL:		fnames->conf_ovwr = False;
     case YES:
	 switch (fnames->op)
	 {
	     case COPY:	errstr = "Error copying"; break;
	     case MOVE: errstr = "Error moving"; break;
	     default: errstr = "Error creating symlink to";
	 }
	 strcpy(from, fnames->directory);
	 if (from[(len = strlen(from)) - 1] != '/')
	     strcat(from, "/");
	 strcat(from, fnames->names[fnames->first]);
	 strcpy(to, fnames->target);
	 devfrom = findDev(from);
	 if (mountDev(devto = findDev(to), False))
	     deverr = devto;
	 else if (mountDev(devfrom, False))
	     deverr = devfrom;
	 if (deverr != -1)
	 {
	     error(fnames->shell, "Cannot mount device on", mntable.devices[deverr].def_mpoint);
	     fnames->first = fnames->n_sel;
	     umountDev(devto, False);
	     break;
	 }
	 if (fnames->dirtarget)  strcat(to, fnames->names[fnames->first]);
	 if (!(lstat(to, &tolstats)))
	 {
	     if (fnames->op != COPY && S_ISDIR(tolstats.st_mode))
		 rdelete(to);
	     else if (fnames->op == LINK || (fnames->op == MOVE && S_ISLNK(tolstats.st_mode)))
	     {
		 unlink(to);
		 fnames->update = True;
	     }
	 }
	 switch (fnames->op)
	 {
	     case COPY:	rcopy(from, to, False); res = 0; break;
	     case MOVE:	res = movefile(from, to); break;
	     default:	res = makeLink(from, to);
	 }
	 if (res)
	 {
	     if (opError(fnames->shell, errstr, from) != YES)
	     {
		 fnames->first = fnames->n_sel;
		 break;
	     }
	 }
	 else  fnames->update = True;
	 umountDev(devto, False);
	 umountDev(devfrom, False);
     case NO:	fnames->first++;
 }
 moveFilesProc(fsel, YES);
}
bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) const
{
    merchant.clear();

    if (!IsInitialized())
        return false;

    // One day we'll support more PKI types, but just
    // x509 for now:
    const EVP_MD* digestAlgorithm = NULL;
    if (paymentRequest.pki_type() == "x509+sha256") {
        digestAlgorithm = EVP_sha256();
    }
    else if (paymentRequest.pki_type() == "x509+sha1") {
        digestAlgorithm = EVP_sha1();
    }
    else if (paymentRequest.pki_type() == "none") {
        qDebug() << "PaymentRequestPlus::getMerchant : Payment request: pki_type == none";
        return false;
    }
    else {
        qDebug() << "PaymentRequestPlus::getMerchant : Payment request: unknown pki_type " << QString::fromStdString(paymentRequest.pki_type());
        return false;
    }

    payments::X509Certificates certChain;
    if (!certChain.ParseFromString(paymentRequest.pki_data())) {
        qDebug() << "PaymentRequestPlus::getMerchant : Payment request: error parsing pki_data";
        return false;
    }

    std::vector<X509*> certs;
    const QDateTime currentTime = QDateTime::currentDateTime();
    for (int i = 0; i < certChain.certificate_size(); i++) {
        QByteArray certData(certChain.certificate(i).data(), certChain.certificate(i).size());
        QSslCertificate qCert(certData, QSsl::Der);
        if (currentTime < qCert.effectiveDate() || currentTime > qCert.expiryDate()) {
            qDebug() << "PaymentRequestPlus::getMerchant : Payment request: certificate expired or not yet active: " << qCert;
            return false;
        }
#if QT_VERSION >= 0x050000
        if (qCert.isBlacklisted()) {
            qDebug() << "PaymentRequestPlus::getMerchant : Payment request: certificate blacklisted: " << qCert;
            return false;
        }
#endif
        const unsigned char *data = (const unsigned char *)certChain.certificate(i).data();
        X509 *cert = d2i_X509(NULL, &data, certChain.certificate(i).size());
        if (cert)
            certs.push_back(cert);
    }
    if (certs.empty()) {
        qDebug() << "PaymentRequestPlus::getMerchant : Payment request: empty certificate chain";
        return false;
    }

    // The first cert is the signing cert, the rest are untrusted certs that chain
    // to a valid root authority. OpenSSL needs them separately.
    STACK_OF(X509) *chain = sk_X509_new_null();
    for (int i = certs.size()-1; i > 0; i--) {
        sk_X509_push(chain, certs[i]);
    }
    X509 *signing_cert = certs[0];

    // Now create a "store context", which is a single use object for checking,
    // load the signing cert into it and verify.
    X509_STORE_CTX *store_ctx = X509_STORE_CTX_new();
    if (!store_ctx) {
        qDebug() << "PaymentRequestPlus::getMerchant : Payment request: error creating X509_STORE_CTX";
        return false;
    }

    char *website = NULL;
    bool fResult = true;
    try
    {
        if (!X509_STORE_CTX_init(store_ctx, certStore, signing_cert, chain))
        {
            int error = X509_STORE_CTX_get_error(store_ctx);
            throw SSLVerifyError(X509_verify_cert_error_string(error));
        }

        // Now do the verification!
        int result = X509_verify_cert(store_ctx);
        if (result != 1) {
            int error = X509_STORE_CTX_get_error(store_ctx);
            throw SSLVerifyError(X509_verify_cert_error_string(error));
        }
        X509_NAME *certname = X509_get_subject_name(signing_cert);

        // Valid cert; check signature:
        payments::PaymentRequest rcopy(paymentRequest); // Copy
        rcopy.set_signature(std::string(""));
        std::string data_to_verify;                     // Everything but the signature
        rcopy.SerializeToString(&data_to_verify);

        EVP_MD_CTX ctx;
        EVP_PKEY *pubkey = X509_get_pubkey(signing_cert);
        EVP_MD_CTX_init(&ctx);
        if (!EVP_VerifyInit_ex(&ctx, digestAlgorithm, NULL) ||
                !EVP_VerifyUpdate(&ctx, data_to_verify.data(), data_to_verify.size()) ||
                !EVP_VerifyFinal(&ctx, (const unsigned char*)paymentRequest.signature().data(), paymentRequest.signature().size(), pubkey)) {

            throw SSLVerifyError("Bad signature, invalid PaymentRequest.");
        }

        // OpenSSL API for getting human printable strings from certs is baroque.
        int textlen = X509_NAME_get_text_by_NID(certname, NID_commonName, NULL, 0);
        website = new char[textlen + 1];
        if (X509_NAME_get_text_by_NID(certname, NID_commonName, website, textlen + 1) == textlen && textlen > 0) {
            merchant = website;
        }
        else {
            throw SSLVerifyError("Bad certificate, missing common name.");
        }
        // TODO: detect EV certificates and set merchant = business name instead of unfriendly NID_commonName ?
    }
    catch (SSLVerifyError& err)
    {
        fResult = false;
        qDebug() << "PaymentRequestPlus::getMerchant : SSL error: " << err.what();
    }

    if (website)
        delete[] website;
    X509_STORE_CTX_free(store_ctx);
    for (unsigned int i = 0; i < certs.size(); i++)
        X509_free(certs[i]);

    return fResult;
}
Esempio n. 19
0
File: pmov.c Progetto: 8l/qbe
int
main()
{
	Ins *i1;
	unsigned long long tm, rm, cnt;
	RMap mend;
	int reg[NIReg], val[NIReg+1];
	int t, i, r, nr;

	tmp = (Tmp[Tmp0+NIReg]){{{0}}};
	for (t=0; t<Tmp0+NIReg; t++)
		if (t >= Tmp0) {
			tmp[t].cls = Kw;
			tmp[t].hint.r = -1;
			tmp[t].hint.m = 0;
			tmp[t].slot = -1;
			sprintf(tmp[t].name, "tmp%d", t-Tmp0+1);
		}

	bsinit_(mbeg.b, Tmp0+NIReg);
	bsinit_(mend.b, Tmp0+NIReg);
	cnt = 0;
	for (tm = 0; tm < 1ull << (2*NIReg); tm++) {
		mbeg.n = 0;
		bszero(mbeg.b);
		ip = ins;

		/* find what temporaries are in copy and
		 * wether or not they are in register
		 */
		for (t=0; t<NIReg; t++)
			switch ((tm >> (2*t)) & 3) {
			case 0:
				/* not in copy, not in reg */
				break;
			case 1:
				/* not in copy, in reg */
				radd(&mbeg, Tmp0+t, t+1);
				break;
			case 2:
				/* in copy, not in reg */
				*ip++ = (Ins){OCopy, TMP(Tmp0+t), {R, R}, Kw};
				break;
			case 3:
				/* in copy, in reg */
				*ip++ = (Ins){OCopy, TMP(Tmp0+t), {R, R}, Kw};
				radd(&mbeg, Tmp0+t, t+1);
				break;
			}

		if (ip == ins)
			/* cancel if the parallel move
			 * is empty
			 */
			goto Nxt;

		/* find registers for temporaries
		 * in mbeg
		 */
		nr = ip - ins;
		rm = (1ull << (nr+1)) - 1;
		for (i=0; i<nr; i++)
			reg[i] = i+1;

		for (;;) {
			/* set registers on copies
			 */
			for (i=0, i1=ins; i1<ip; i1++, i++)
				i1->arg[0] = TMP(reg[i]);

			/* compile the parallel move
			 */
			rcopy(&mend, &mbeg);
			dopm(&dummyb, ip-1, &mend);
			cnt++;

			/* check that mend contain mappings for
			 * source registers and does not map any
			 * assigned temporary, then check that
			 * all temporaries in mend are mapped in
			 * mbeg and not used in the copy
			 */
			for (i1=ins; i1<ip; i1++) {
				r = i1->arg[0].val;
				assert(rfree(&mend, r) == r);
				t = i1->to.val;
				assert(!bshas(mend.b, t));
			}
			for (i=0; i<mend.n; i++) {
				t = mend.t[i];
				assert(bshas(mbeg.b, t));
				t -= Tmp0;
				assert(((tm >> (2*t)) & 3) == 1);
			}

			/* execute the code generated and check
			 * that all assigned temporaries got their
			 * value, and that all live variables's
			 * content got preserved
			 */
			 for (i=1; i<=NIReg; i++)
			 	val[i] = i;
			 iexec(val);
			 for (i1=ins; i1<ip; i1++) {
			 	t = i1->to.val;
			 	r = rfind(&mbeg, t);
			 	if (r != -1)
			 		assert(val[r] == i1->arg[0].val);
			 }
			 for (i=0; i<mend.n; i++) {
			 	t = mend.t[i];
			 	r = mend.r[i];
			 	assert(val[t-Tmp0+1] == r);
			 }

			/* find the next register assignment */
			i = nr - 1;
			for (;;) {
				r = reg[i];
				rm &= ~(1ull<<r);
				do
					r++;
				while (r <= NIReg && (rm & (1ull<<r)));
				if (r == NIReg+1) {
					if (i == 0)
						goto Nxt;
					i--;
				} else {
					rm |= (1ull<<r);
					reg[i++] = r;
					break;
				}
			}
			for (; i<nr; i++)
				for (r=1; r<=NIReg; r++)
					if (!(rm & (1ull<<r))) {
						rm |= (1ull<<r);
						reg[i] = r;
						break;
					}
		}
	Nxt:	freeall();
	}
	printf("%llu tests successful!\n", cnt);
	exit(0);
}
Esempio n. 20
0
File: add.c Progetto: jpflori/pari
INLINE GEN
rcopy_sign(GEN x, long sx) { GEN y = rcopy(x); setsigne(y,sx); return y; }
Esempio n. 21
0
void FM_Mc2WayCutRefine(ctrl_t *ctrl, graph_t *graph, real_t *ntpwgts, idx_t niter)
{
    idx_t i, ii, j, k, l, kwgt, nvtxs, ncon, nbnd, nswaps, from, to, pass,
          me, limit, tmp, cnum;
    idx_t *xadj, *adjncy, *vwgt, *adjwgt, *pwgts, *where, *id, *ed,
          *bndptr, *bndind;
    idx_t *moved, *swaps, *perm, *qnum;
    idx_t higain, mincut, initcut, newcut, mincutorder;
    real_t *invtvwgt, *ubfactors, *minbalv, *newbalv;
    real_t origbal, minbal, newbal, rgain, ffactor;
    rpq_t **queues;

    WCOREPUSH;

    nvtxs    = graph->nvtxs;
    ncon     = graph->ncon;
    xadj     = graph->xadj;
    vwgt     = graph->vwgt;
    adjncy   = graph->adjncy;
    adjwgt   = graph->adjwgt;
    invtvwgt = graph->invtvwgt;
    where    = graph->where;
    id       = graph->id;
    ed       = graph->ed;
    pwgts    = graph->pwgts;
    bndptr   = graph->bndptr;
    bndind   = graph->bndind;

    moved     = iwspacemalloc(ctrl, nvtxs);
    swaps     = iwspacemalloc(ctrl, nvtxs);
    perm      = iwspacemalloc(ctrl, nvtxs);
    qnum      = iwspacemalloc(ctrl, nvtxs);
    ubfactors = rwspacemalloc(ctrl, ncon);
    newbalv   = rwspacemalloc(ctrl, ncon);
    minbalv   = rwspacemalloc(ctrl, ncon);

    limit = gk_min(gk_max(0.01*nvtxs, 25), 150);


    /* Determine a fudge factor to allow the refinement routines to get out
       of tight balancing constraints. */
    ffactor = .5/gk_max(20, nvtxs);

    /* Initialize the queues */
    queues = (rpq_t **)wspacemalloc(ctrl, 2*ncon*sizeof(rpq_t *));
    for (i=0; i<2*ncon; i++)
        queues[i] = rpqCreate(nvtxs);
    for (i=0; i<nvtxs; i++)
        qnum[i] = iargmax_nrm(ncon, vwgt+i*ncon, invtvwgt);

    /* Determine the unbalance tolerance for each constraint. The tolerance is
       equal to the maximum of the original load imbalance and the user-supplied
       allowed tolerance. The rationale behind this approach is to allow the
       refinement routine to improve the cut, without having to worry about fixing
       load imbalance problems. The load imbalance is addressed by the balancing
       routines. */
    origbal = ComputeLoadImbalanceDiffVec(graph, 2, ctrl->pijbm, ctrl->ubfactors, ubfactors);
    for (i=0; i<ncon; i++)
        ubfactors[i] = (ubfactors[i] > 0 ? ctrl->ubfactors[i]+ubfactors[i] : ctrl->ubfactors[i]);


    IFSET(ctrl->dbglvl, METIS_DBG_REFINE,
          Print2WayRefineStats(ctrl, graph, ntpwgts, origbal, -2));

    iset(nvtxs, -1, moved);
    for (pass=0; pass<niter; pass++) { /* Do a number of passes */
        for (i=0; i<2*ncon; i++)
            rpqReset(queues[i]);

        mincutorder = -1;
        newcut = mincut = initcut = graph->mincut;

        minbal = ComputeLoadImbalanceDiffVec(graph, 2, ctrl->pijbm, ubfactors, minbalv);

        ASSERT(ComputeCut(graph, where) == graph->mincut);
        ASSERT(CheckBnd(graph));

        /* Insert boundary nodes in the priority queues */
        nbnd = graph->nbnd;
        irandArrayPermute(nbnd, perm, nbnd/5, 1);
        for (ii=0; ii<nbnd; ii++) {
            i = bndind[perm[ii]];
            ASSERT(ed[i] > 0 || id[i] == 0);
            ASSERT(bndptr[i] != -1);
            //rgain = 1.0*(ed[i]-id[i])/sqrt(vwgt[i*ncon+qnum[i]]+1);
            //rgain = (ed[i]-id[i] > 0 ? 1.0*(ed[i]-id[i])/sqrt(vwgt[i*ncon+qnum[i]]+1) : ed[i]-id[i]);
            rgain = ed[i]-id[i];
            rpqInsert(queues[2*qnum[i]+where[i]], i, rgain);
        }

        for (nswaps=0; nswaps<nvtxs; nswaps++) {
            SelectQueue(graph, ctrl->pijbm, ubfactors, queues, &from, &cnum);

            to = (from+1)%2;

            if (from == -1 || (higain = rpqGetTop(queues[2*cnum+from])) == -1)
                break;
            ASSERT(bndptr[higain] != -1);

            newcut -= (ed[higain]-id[higain]);

            iaxpy(ncon,  1, vwgt+higain*ncon, 1, pwgts+to*ncon,   1);
            iaxpy(ncon, -1, vwgt+higain*ncon, 1, pwgts+from*ncon, 1);
            newbal = ComputeLoadImbalanceDiffVec(graph, 2, ctrl->pijbm, ubfactors, newbalv);

            if ((newcut < mincut && newbal <= ffactor) ||
                    (newcut == mincut && (newbal < minbal ||
                                          (newbal == minbal && BetterBalance2Way(ncon, minbalv, newbalv))))) {
                mincut      = newcut;
                minbal      = newbal;
                mincutorder = nswaps;
                rcopy(ncon, newbalv, minbalv);
            }
            else if (nswaps-mincutorder > limit) { /* We hit the limit, undo last move */
                newcut += (ed[higain]-id[higain]);
                iaxpy(ncon,  1, vwgt+higain*ncon, 1, pwgts+from*ncon, 1);
                iaxpy(ncon, -1, vwgt+higain*ncon, 1, pwgts+to*ncon,   1);
                break;
            }

            where[higain] = to;
            moved[higain] = nswaps;
            swaps[nswaps] = higain;

            if (ctrl->dbglvl&METIS_DBG_MOVEINFO) {
                printf("Moved%6"PRIDX" from %"PRIDX"(%"PRIDX") Gain:%5"PRIDX", "
                       "Cut:%5"PRIDX", NPwgts:", higain, from, cnum, ed[higain]-id[higain], newcut);
                for (l=0; l<ncon; l++)
                    printf("(%.3"PRREAL" %.3"PRREAL")", pwgts[l]*invtvwgt[l], pwgts[ncon+l]*invtvwgt[l]);
                printf(" %+.3"PRREAL" LB: %.3"PRREAL"(%+.3"PRREAL")\n",
                       minbal, ComputeLoadImbalance(graph, 2, ctrl->pijbm), newbal);
            }


            /**************************************************************
            * Update the id[i]/ed[i] values of the affected nodes
            ***************************************************************/
            SWAP(id[higain], ed[higain], tmp);
            if (ed[higain] == 0 && xadj[higain] < xadj[higain+1])
                BNDDelete(nbnd, bndind,  bndptr, higain);

            for (j=xadj[higain]; j<xadj[higain+1]; j++) {
                k = adjncy[j];

                kwgt = (to == where[k] ? adjwgt[j] : -adjwgt[j]);
                INC_DEC(id[k], ed[k], kwgt);

                /* Update its boundary information and queue position */
                if (bndptr[k] != -1) { /* If k was a boundary vertex */
                    if (ed[k] == 0) { /* Not a boundary vertex any more */
                        BNDDelete(nbnd, bndind, bndptr, k);
                        if (moved[k] == -1)  /* Remove it if in the queues */
                            rpqDelete(queues[2*qnum[k]+where[k]], k);
                    }
                    else { /* If it has not been moved, update its position in the queue */
                        if (moved[k] == -1) {
                            //rgain = 1.0*(ed[k]-id[k])/sqrt(vwgt[k*ncon+qnum[k]]+1);
                            //rgain = (ed[k]-id[k] > 0 ?
                            //              1.0*(ed[k]-id[k])/sqrt(vwgt[k*ncon+qnum[k]]+1) : ed[k]-id[k]);
                            rgain = ed[k]-id[k];
                            rpqUpdate(queues[2*qnum[k]+where[k]], k, rgain);
                        }
                    }
                }
                else {
                    if (ed[k] > 0) {  /* It will now become a boundary vertex */
                        BNDInsert(nbnd, bndind, bndptr, k);
                        if (moved[k] == -1) {
                            //rgain = 1.0*(ed[k]-id[k])/sqrt(vwgt[k*ncon+qnum[k]]+1);
                            //rgain = (ed[k]-id[k] > 0 ?
                            //              1.0*(ed[k]-id[k])/sqrt(vwgt[k*ncon+qnum[k]]+1) : ed[k]-id[k]);
                            rgain = ed[k]-id[k];
                            rpqInsert(queues[2*qnum[k]+where[k]], k, rgain);
                        }
                    }
                }
            }

        }


        /****************************************************************
        * Roll back computations
        *****************************************************************/
        for (i=0; i<nswaps; i++)
            moved[swaps[i]] = -1;  /* reset moved array */
        for (nswaps--; nswaps>mincutorder; nswaps--) {
            higain = swaps[nswaps];

            to = where[higain] = (where[higain]+1)%2;
            SWAP(id[higain], ed[higain], tmp);
            if (ed[higain] == 0 && bndptr[higain] != -1 && xadj[higain] < xadj[higain+1])
                BNDDelete(nbnd, bndind,  bndptr, higain);
            else if (ed[higain] > 0 && bndptr[higain] == -1)
                BNDInsert(nbnd, bndind,  bndptr, higain);

            iaxpy(ncon,  1, vwgt+higain*ncon, 1, pwgts+to*ncon,         1);
            iaxpy(ncon, -1, vwgt+higain*ncon, 1, pwgts+((to+1)%2)*ncon, 1);
            for (j=xadj[higain]; j<xadj[higain+1]; j++) {
                k = adjncy[j];

                kwgt = (to == where[k] ? adjwgt[j] : -adjwgt[j]);
                INC_DEC(id[k], ed[k], kwgt);

                if (bndptr[k] != -1 && ed[k] == 0)
                    BNDDelete(nbnd, bndind, bndptr, k);
                if (bndptr[k] == -1 && ed[k] > 0)
                    BNDInsert(nbnd, bndind, bndptr, k);
            }
        }

        graph->mincut = mincut;
        graph->nbnd   = nbnd;

        IFSET(ctrl->dbglvl, METIS_DBG_REFINE,
              Print2WayRefineStats(ctrl, graph, ntpwgts, minbal, mincutorder));

        if (mincutorder <= 0 || mincut == initcut)
            break;
    }

    for (i=0; i<2*ncon; i++)
        rpqDestroy(queues[i]);

    WCOREPOP;
}
Esempio n. 22
0
void moveFilesProc(XtPointer fsel, int conf)
{
 SelFileNamesRec *fnames = (SelFileNamesRec *) fsel;
 struct stat tostats, tolstats, frstats;
 char from[MAXPATHLEN], to[MAXPATHLEN];
 String name, cwd;
 String op_name, from_err, to_err;
 size_t toend, fromend;
 int devto, devfrom, deverr = -1, i, perm, res;
 Boolean is_dir, is_link;

 if (conf != YES || !fnames->op)
 {
     freeSelFiles(fnames);
     return;
 }
 if (chdir(fnames->directory))
 {
     sysError(fnames->shell, "System error:");
     freeSelFiles(fnames);
     return;
 }
 chdir(user.home);
 switch (fnames->op)
 {
     case COPY:
	 op_name = "Copy:";
	 from_err = "Error copying";
	 to_err = "Error copying to";
	 break;
     case MOVE:
	 op_name = "Move:";
	 from_err = "Error moving";
	 to_err = "Error moving to";
	 break;
     default:  /* i.e. LINK */
	 op_name = "Link:";
	 from_err = "Error creating symlink to";
	 to_err = "Error creating symlink in";
 }
 if (fnames->target[0] != '/' && fnames->target[0] != '~' && fnames->target != 0)
 {
     strcpy(to, fnames->directory);
     if (to[strlen(to)-1] != '/')  strcat(to, "/");
 }
 else to[0] = 0;
 strcat(to, fnames->target);
 fnexpand(to);
 if (!(cwd = absolutePath(to)))
 {
     error(fnames->shell, no_target, to);
     freeSelFiles(fnames);
     return;
 }
 strcpy(to, cwd);
 XTFREE(cwd);
 fromend = strlen(strcpy(from, fnames->directory));
 if (from[fromend-1] != '/')
 {
     from[fromend++] = '/';
     from[fromend] = 0;
 }
 devfrom = findDev(from);
 if (mountDev(devto = findDev(to), False))
     deverr = devto;
 else if (mountDev(devfrom, False))
     deverr = devfrom;
 if (deverr != -1)
 {
     error(fnames->shell, "Cannot mount device on", mntable.devices[deverr].def_mpoint);
     umountDev(devto, False);
     freeSelFiles(fnames);
     return;
 }
 if (!(stat(to, &tostats)) && S_ISDIR(tostats.st_mode))
 {
     if (chdir(to) || !(perm = permission(&tostats, P_WRITE)))
     {
	 chdir(user.home);
	 if (!perm)
	     error(fnames->shell, "You have no write permission for ", to);
	 else  sysError(fnames->shell, "System error:");
	 umountDev(devto, False);
	 umountDev(devfrom, False);
	 freeSelFiles(fnames);
	 return;
     }
     chdir(user.home);
     fnames->dirtarget = True;
     toend = strlen(to);
     if (to[toend-1] != '/')
     {
	 to[toend++] = '/';
	 to[toend] = 0;
     }
 }
 else if (fnames->n_sel == 1)  fnames->dirtarget = False;
 else
 {
     error(fnames->shell, op_name, "Target for multiple files must be a folder");
     umountDev(devto, False);
     umountDev(devfrom, False);
     freeSelFiles(fnames);
     return;
 }
 if (!fnames->first)  zzz();
 XTFREE(fnames->target);
 fnames->target = XtNewString(to);
 for (i = fnames->first; i < fnames->n_sel; i++)
 {
     name = fnames->names[i];
     if (fnames->op != LINK && (!strcmp(name, ".") || !strcmp(name, "..")))
     {
	 error(fnames->shell, "Cannot move or copy . or ..", NULL);
	 continue;
     }
     strcpy(from+fromend, name);
     if (fnames->dirtarget)
     {
	 if (fnames->op != LINK && prefix(from, to))
	 {
	     String err_str, format = "Cannot move or copy %s to";
	     err_str = (String) XtMalloc((strlen(format) + strlen(from)) * sizeof(char));
	     sprintf(err_str, format, from);
	     error(fnames->shell, err_str, to);
	     XTFREE(err_str);
	     umountDev(devto, False);
	     umountDev(devfrom, False);
	     freeSelFiles(fnames);
	     wakeUp();
	     return;
	 }
	 strcpy(to+toend, name);
     }
     if (!(lstat(to, &tolstats)))
     {
	 fnames->first = i;
	 is_dir = False;
	 if (!(stat(to, &tostats)))
	 {
	     if (S_ISDIR(tostats.st_mode))
		 is_dir = True;
	     if (!stat(from, &frstats) && tostats.st_ino == frstats.st_ino)
	     {
		 error(fnames->shell, op_name, "Source and destination are identical");
		 umountDev(devto, False);
		 umountDev(devfrom, False);
		 freeSelFiles(fnames);
		 wakeUp();
		 return;
	     }
	 }
	 if (S_ISLNK(tolstats.st_mode))
	     is_link = True;
	 else  is_link = False;

	 if (fnames->conf_ovwr || (is_dir && (!is_link || fnames->op == COPY) && resources.confirm_delete_folder))
	     overwriteDialog(fnames, to, (fnames->op == COPY && is_dir && (lstat(from, &frstats) || !S_ISDIR(frstats.st_mode)))?
			     "File copy:" : op_name,
			     is_dir && (!is_link || fnames->op == COPY));
	 else overwriteProc(fsel, YES);
	 umountDev(devto, False);
	 umountDev(devfrom, False);
	 return;
     }
     switch (fnames->op)
     {
	 case COPY:	rcopy(from, to, False); res = 0; break;
	 case MOVE:	res = movefile(from, to); break;
	 default:	res = makeLink(from, to);
     }
     if (res)
     {
	 if (opError(fnames->shell, from_err, name) != YES)
	     break;
     }
     else  fnames->update = True;
 }
 umountDev(devto, False);
 umountDev(devfrom, False);
 if (fnames->update)
 {
     if (fnames->op == COPY)
	 intUpdate(CHECK_DIR);		/* Check for new subdirectories */
     if (fnames->op == MOVE)
	 markForUpdate(fnames->directory, CHECK_FILES);
     markForUpdate(to, RESHOW);
     if (fnames->op != COPY)
	 intUpdate(CHECK_DIR);
 }
 freeSelFiles(fnames);
 wakeUp();
}