示例#1
0
文件: dojump.c 项目: keparo/gcc
void
jumpifnot (tree exp, rtx label, int prob)
{
  do_jump (exp, label, NULL_RTX, inv (prob));
}
示例#2
0
void kernel(mat_ZZ_pE& X, const mat_ZZ_pE& A)
{
   long m = A.NumRows();
   long n = A.NumCols();

   mat_ZZ_pE M;
   long r;

   transpose(M, A);
   r = gauss(M);

   X.SetDims(m-r, m);

   long i, j, k, s;
   ZZ_pX t1, t2;

   ZZ_pE T3;

   vec_long D;
   D.SetLength(m);
   for (j = 0; j < m; j++) D[j] = -1;

   vec_ZZ_pE inverses;
   inverses.SetLength(m);

   j = -1;
   for (i = 0; i < r; i++) {
      do {
         j++;
      } while (IsZero(M[i][j]));

      D[j] = i;
      inv(inverses[j], M[i][j]); 
   }

   for (k = 0; k < m-r; k++) {
      vec_ZZ_pE& v = X[k];
      long pos = 0;
      for (j = m-1; j >= 0; j--) {
         if (D[j] == -1) {
            if (pos == k)
               set(v[j]);
            else
               clear(v[j]);
            pos++;
         }
         else {
            i = D[j];

            clear(t1);

            for (s = j+1; s < m; s++) {
               mul(t2, rep(v[s]), rep(M[i][s]));
               add(t1, t1, t2);
            }

            conv(T3, t1);
            mul(T3, T3, inverses[j]);
            negate(v[j], T3);
         }
      }
   }
}
示例#3
0
    //Class constructor
	TimeSegmentation(Tobj &G, Col <T1> map_in, Col <T1> timeVec_in, uword a, uword b, uword c, uword interptype = 1,
					 uword shots = 1)
    {
		cout << "Entering Class constructor" << endl;
	    n1 = a; //Data size
	    n2 = b;//Image size
	    L = c; //number of time segments
	    type = interptype; // type of time segmentation performed
	    Nshots = shots; // number of shots
	    obj = &G;
	    fieldMap = map_in;
    	cout << "N1 = " << n1 << endl;
		cout << "N2 = " << n2 << endl;
		cout << "L = " << L << endl;


		AA.set_size(n1, L); //time segments weights
	    timeVec = timeVec_in;
	    T_min =timeVec.min();
	    T1 rangt = timeVec.max()-T_min;
		tau = (rangt + datum::eps) / (L - 1); // it was L-1 before
	    timeVec = timeVec-T_min;

	    uword NOneShot = n1/Nshots;
	    if (L==1) {
		    tau = 0;
		    AA.ones();
	    }
	    else {
			Mat <CxT1> tempAA(NOneShot, L);
		    if (type==1) {// Hanning interpolator
			    cout << "Hanning interpolation" << endl;
			    for (unsigned int ii = 0; ii<L; ii++) {
				    for (unsigned int jj = 0; jj<NOneShot; jj++) {
					    if ((std::abs(timeVec(jj)-((ii)*tau)))<=tau) {
						    tempAA(jj, ii) = 0.5+0.5*std::cos((datum::pi)*(timeVec(jj)-((ii)*tau))/tau);
					    }
					    else {
						    tempAA(jj, ii) = 0.0;
					    }
				    }
			    }
			    AA = repmat(tempAA, Nshots, 1);
		    }
		    else if (type==2) { // Min-max interpolator: Exact LS interpolator

			    cout << "Min Max time segmentation" << endl;

			    Mat <CxT1> Ltp;
			    Ltp.ones(1, L);
			    Col <CxT1> ggtp;
			    ggtp.ones(n2, 1);
			    Mat <CxT1> gg;
			    gg = exp(i*fieldMap*tau)*Ltp;
			    Mat <CxT1> iGTGGT;
			    iGTGGT.set_size(L+1, n2);
			    Mat <CxT1> gl;
			    gl.zeros(n2, L);


			    for (unsigned int ii = 0; ii<L; ii++) {
				    for (unsigned int jj = 0; jj<n2; jj++) {
					    gl(jj, ii) = pow(gg(jj, ii), (T1) (ii+1));
				    }
			    }

			    Mat <CxT1> G;
			    G.set_size(n2, L);

			    for (unsigned int jj = 0; jj<L; jj++) {
				    if (jj==0) {
					    G.col(jj) = ggtp;
				    }
				    else {
					    G.col(jj) = gl.col(jj-1);
				    }
			    }

			    Col <CxT1> glsum;
			    Mat <CxT1> GTG;
			    GTG.zeros(L, L);
			    GTG.diag(0) += n2;
			    glsum = sum(gl.t(), 1);
				Mat <CxT1> GTGtp(L, L);
				for (unsigned int ii = 0; ii < (L - 1); ii++) {
					GTGtp.zeros();
				    GTGtp.diag(-(T1) (ii+1)) += glsum(ii);
				    GTGtp.diag((T1) (ii+1)) += std::conj(glsum(ii));
				    GTG = GTG+GTGtp;
			    }

			    T1 rcn = 1/cond(GTG);
			    if (rcn>10*2e-16) { //condition number of GTG
				    iGTGGT = inv(GTG)*G.t();

			    }
			    else {
				    iGTGGT = pinv(GTG)*G.t(); // pseudo inverse
			    }


			    Mat <CxT1> iGTGGTtp;
			    Mat <CxT1> ftp;
			    Col <CxT1> res, temp;

			    for (unsigned int ii = 0; ii<NOneShot; ii++) {
				    ftp = exp(i*fieldMap*timeVec(ii));
				    res = iGTGGT*ftp;
				    tempAA.row(ii) = res.t();
			    }
			    AA = repmat(tempAA, Nshots, 1);
		    }
	    }
		savemat("aamat.mat", "AA", vectorise(AA));
		cout << "Exiting class constructor." << endl;
    }
示例#4
0
文件: dojump.c 项目: boomeer/gcc
void
do_compare_rtx_and_jump (rtx op0, rtx op1, enum rtx_code code, int unsignedp,
			 machine_mode mode, rtx size,
			 rtx_code_label *if_false_label,
			 rtx_code_label *if_true_label, int prob)
{
  rtx tem;
  rtx_code_label *dummy_label = NULL;

  /* Reverse the comparison if that is safe and we want to jump if it is
     false.  Also convert to the reverse comparison if the target can
     implement it.  */
  if ((! if_true_label
       || ! can_compare_p (code, mode, ccp_jump))
      && (! FLOAT_MODE_P (mode)
	  || code == ORDERED || code == UNORDERED
	  || (! HONOR_NANS (mode) && (code == LTGT || code == UNEQ))
	  || (! HONOR_SNANS (mode) && (code == EQ || code == NE))))
    {
      enum rtx_code rcode;
      if (FLOAT_MODE_P (mode))
        rcode = reverse_condition_maybe_unordered (code);
      else
        rcode = reverse_condition (code);

      /* Canonicalize to UNORDERED for the libcall.  */
      if (can_compare_p (rcode, mode, ccp_jump)
	  || (code == ORDERED && ! can_compare_p (ORDERED, mode, ccp_jump)))
	{
	  std::swap (if_true_label, if_false_label);
	  code = rcode;
	  prob = inv (prob);
	}
    }

  /* If one operand is constant, make it the second one.  Only do this
     if the other operand is not constant as well.  */

  if (swap_commutative_operands_p (op0, op1))
    {
      std::swap (op0, op1);
      code = swap_condition (code);
    }

  do_pending_stack_adjust ();

  code = unsignedp ? unsigned_condition (code) : code;
  if (0 != (tem = simplify_relational_operation (code, mode, VOIDmode,
						 op0, op1)))
    {
      if (CONSTANT_P (tem))
	{
	  rtx_code_label *label = (tem == const0_rtx
				   || tem == CONST0_RTX (mode))
					? if_false_label : if_true_label;
	  if (label)
	    emit_jump (label);
	  return;
	}

      code = GET_CODE (tem);
      mode = GET_MODE (tem);
      op0 = XEXP (tem, 0);
      op1 = XEXP (tem, 1);
      unsignedp = (code == GTU || code == LTU || code == GEU || code == LEU);
    }

  if (! if_true_label)
    dummy_label = if_true_label = gen_label_rtx ();

  if (GET_MODE_CLASS (mode) == MODE_INT
      && ! can_compare_p (code, mode, ccp_jump))
    {
      switch (code)
	{
	case LTU:
	  do_jump_by_parts_greater_rtx (mode, 1, op1, op0,
					if_false_label, if_true_label, prob);
	  break;

	case LEU:
	  do_jump_by_parts_greater_rtx (mode, 1, op0, op1,
					if_true_label, if_false_label,
					inv (prob));
	  break;

	case GTU:
	  do_jump_by_parts_greater_rtx (mode, 1, op0, op1,
					if_false_label, if_true_label, prob);
	  break;

	case GEU:
	  do_jump_by_parts_greater_rtx (mode, 1, op1, op0,
					if_true_label, if_false_label,
					inv (prob));
	  break;

	case LT:
	  do_jump_by_parts_greater_rtx (mode, 0, op1, op0,
					if_false_label, if_true_label, prob);
	  break;

	case LE:
	  do_jump_by_parts_greater_rtx (mode, 0, op0, op1,
					if_true_label, if_false_label,
					inv (prob));
	  break;

	case GT:
	  do_jump_by_parts_greater_rtx (mode, 0, op0, op1,
					if_false_label, if_true_label, prob);
	  break;

	case GE:
	  do_jump_by_parts_greater_rtx (mode, 0, op1, op0,
					if_true_label, if_false_label,
					inv (prob));
	  break;

	case EQ:
	  do_jump_by_parts_equality_rtx (mode, op0, op1, if_false_label,
					 if_true_label, prob);
	  break;

	case NE:
	  do_jump_by_parts_equality_rtx (mode, op0, op1, if_true_label,
					 if_false_label, inv (prob));
	  break;

	default:
	  gcc_unreachable ();
	}
    }
  else
    {
      if (SCALAR_FLOAT_MODE_P (mode)
	  && ! can_compare_p (code, mode, ccp_jump)
	  && can_compare_p (swap_condition (code), mode, ccp_jump))
	{
	  code = swap_condition (code);
	  std::swap (op0, op1);
	}
      else if (SCALAR_FLOAT_MODE_P (mode)
	       && ! can_compare_p (code, mode, ccp_jump)
	       /* Never split ORDERED and UNORDERED.
		  These must be implemented.  */
	       && (code != ORDERED && code != UNORDERED)
               /* Split a floating-point comparison if
		  we can jump on other conditions...  */
	       && (have_insn_for (COMPARE, mode)
	           /* ... or if there is no libcall for it.  */
	           || code_to_optab (code) == unknown_optab))
        {
	  enum rtx_code first_code;
	  bool and_them = split_comparison (code, mode, &first_code, &code);

	  /* If there are no NaNs, the first comparison should always fall
	     through.  */
	  if (!HONOR_NANS (mode))
	    gcc_assert (first_code == (and_them ? ORDERED : UNORDERED));

	  else
	    {
	      int first_prob = prob;
	      if (first_code == UNORDERED)
		first_prob = REG_BR_PROB_BASE / 100;
	      else if (first_code == ORDERED)
		first_prob = REG_BR_PROB_BASE - REG_BR_PROB_BASE / 100;
	      if (and_them)
		{
		  rtx_code_label *dest_label;
		  /* If we only jump if true, just bypass the second jump.  */
		  if (! if_false_label)
		    {
		      if (! dummy_label)
		        dummy_label = gen_label_rtx ();
		      dest_label = dummy_label;
		    }
		  else
		    dest_label = if_false_label;
                  do_compare_rtx_and_jump (op0, op1, first_code, unsignedp, mode,
					   size, dest_label, NULL, first_prob);
		}
              else
                do_compare_rtx_and_jump (op0, op1, first_code, unsignedp, mode,
					 size, NULL, if_true_label, first_prob);
	    }
	}

      emit_cmp_and_jump_insns (op0, op1, code, size, mode, unsignedp,
			       if_true_label, prob);
    }

  if (if_false_label)
    emit_jump (if_false_label);
  if (dummy_label)
    emit_label (dummy_label);
}
int LinearAffineEq::checkInvertibleLinear(const bset & Ua,   const bset & Ub,
							  	  	  	  smap & mapA,       smap & mapB,
							  	  	  	  bsetElem * S1,     bsetElem * S1inv,
							  	  	  	  bsetElem * S2,     bsetElem * S2inv,
							  	  	  	  mat_GF2 & Ta, 	 mat_GF2 & Tb,
							  	  	  	  mat_GF2 & Tbinv,   smap & mapBinv,
							  	  	  	  bool AisA){
	// Extract linearly independent vectors, to determine mapping.
	// We need matrix consisting of Avect to be invertible in order to determine
	// matrix representation of transformation.
	bset Avect = extractLinearlyIndependent(mapA);
	if (verbosity) {
		cout << "Size of linearly independent vectors: " << Avect.size() << endl;
		LinearAffineEq::dumpSet(Avect);
	}

	// Derive matrix representation of transformation, if possible
	//
	// Ta * Ainp = Aout => Ta = Aout * Ainp^{-1}
	mat_GF2 Ainp = LinearAffineEq::vectorSet2GF2matrix(Avect, 8), AinpInv;
	mat_GF2 Aout = LinearAffineEq::values2GF2matrix(Avect, mapA, 8);
	mat_GF2 TAinv;
	GF2 det;

	// Dimension check, each matrix has to have exactly 8 rows (dimension) and at least 8 columns
	// (number of equations, sample points)
	if (       Ainp.NumCols() < dim || Ainp.NumRows() != dim
			|| Aout.NumCols() < dim || Aout.NumRows() != dim){
		if (verbosity) cout << "Dimension mismatch for Ainp || Aout matrices " << endl;
		return -1;
	}

	if (verbosity){
		cout << "Input matrix: " << endl;
		dumpMatrix(Ainp);
		cout << "Output matrix: " << endl;
		dumpMatrix(Aout);
	}

	// invertible?
	inv(det, AinpInv, Ainp);
	if (det == 0) {
		if (verbosity) cout << "A Matrix is not invertible! " << endl;
		return -2;
	}

	if (verbosity){
		cout << "Inverse matrix: " << endl;
		dumpMatrix(AinpInv);
	}

	// obtain linear transformation
	Ta = Aout * AinpInv;
	if (verbosity) {
		cout << "Ta matrix: " << endl;
		dumpMatrix(Ta);
	}

	// invertible?
	inv(det, TAinv, Ta);
	if (det==0){
		if (verbosity) cout << "Transformation is not linear & invertible!" << endl;
		return -3;
	}

	if (verbosity){
		cout << "Transformation matrix repr. obtained!!!" << endl;
		dumpMatrix(Ta);
	}

	//
	// A is known (matrix representation), build lookup table
	//
	if (buildLookupTableAndCheck(Ta, 0, mapA)<0){
		return -4;
	}

	//
	// Deriving mapping B from mapping A that is complete now and in matrix form.
	//
	// B * S2 = S1 * A
	// B(x) = S1 * A * S2^{-1} (x)
	// From this we derive mapping for B for basis vectors directly.
	//
	// Or B and A are swapped here and we want to compute values for A(x)
	// knowing mapping for B(x) (AisA==false)
	//
	// A(x) = S1inv * B * S2 (x)
	//
	Tb.SetDims(dim,dim);
	for(unsigned int i=0; i<dim; i++){
		bsetElem base = 1 << i;
		bsetElem res = AisA ? S1[mapA[S2inv[base]]] : S1inv[mapA[S2[base]]];
		for(unsigned int j=0; j<dim; j++){
			Tb.put(j, i, (res & (1<<j)) > 0 ? 1 : 0);
		}
	}

	if (verbosity){
		cout << "Mapping B derived" << endl;
		dumpMatrix(Tb);
	}

	// Transformation B invertibility test.
	// Inversion is needed for final test for relations properties with S-boxes.
	// If AisA==false, it does not mind, both relations has to be invertible.
	inv(det, Tbinv, Tb);
	if (det==0){
		if (verbosity) cout << "B is not linear invertible transformation, cannot create inversion." << endl;
		return -4;
	}

	// build lookup table for B and check already precomputed values
	if (buildLookupTableAndCheck(Tb, 0, mapB)<0){
		return -4;
	}

	// Whole range test for holding desired properties with Sboxes for which
	// they were designed.
	// For this we also need B^{-1} transformation.
	//
	// We apply this equation here:
	// B^{-1} * S1 * A = S2
	//
	// If AisA==false, we have to reverse mapping here, Ta, Tb, Tainv, Tbinv are swapped,
	// but relations works only according to equations. We need to return mapBinv for
	// real B mapping (B^{-1} is needed to verify relations).
	if (AisA){
		buildLookupTableAndCheck(Tbinv, 0, mapBinv);
	} else {
		mapBinv.clear();
		buildLookupTableAndCheck(TAinv, 0, mapBinv);
		Tbinv = TAinv;
	}

	//
	// Again take swapping A and B into account.
	//
	if (verbosity) cout << "Testing matrix representation with |Ua| = " << Ua.size() << " and |Ub| = " << Ub.size() << endl;
	for(bsetElem iter = 0; iter < size; iter++){
		bsetElem desiredResult = S2[iter];
		bsetElem myResult = AisA ? mapBinv[S1[mapA[iter]]] : mapBinv[S1[mapB[iter]]];
		if (desiredResult!=myResult){
			if (verbosity){
				cout << "Problem with relations, it does not work for: " << iter << endl;
				cout << "S2["<<iter<<"]=           " << desiredResult << endl;
				cout << "B^{-1}[S1[A["<<iter<<"]]]=" << myResult << endl;
			}

			return -5;
		}
	}

	return 0;
}
示例#6
0
文件: dojump.c 项目: boomeer/gcc
void
jumpifnot_1 (enum tree_code code, tree op0, tree op1, rtx_code_label *label,
	     int prob)
{
  do_jump_1 (code, op0, op1, label, NULL, inv (prob));
}
示例#7
0
文件: dojump.c 项目: boomeer/gcc
void
do_jump (tree exp, rtx_code_label *if_false_label,
	 rtx_code_label *if_true_label, int prob)
{
  enum tree_code code = TREE_CODE (exp);
  rtx temp;
  int i;
  tree type;
  machine_mode mode;
  rtx_code_label *drop_through_label = NULL;

  switch (code)
    {
    case ERROR_MARK:
      break;

    case INTEGER_CST:
      {
	rtx_code_label *lab = integer_zerop (exp) ? if_false_label
						  : if_true_label;
	if (lab)
	  emit_jump (lab);
	break;
      }

#if 0
      /* This is not true with #pragma weak  */
    case ADDR_EXPR:
      /* The address of something can never be zero.  */
      if (if_true_label)
        emit_jump (if_true_label);
      break;
#endif

    case NOP_EXPR:
      if (TREE_CODE (TREE_OPERAND (exp, 0)) == COMPONENT_REF
          || TREE_CODE (TREE_OPERAND (exp, 0)) == BIT_FIELD_REF
          || TREE_CODE (TREE_OPERAND (exp, 0)) == ARRAY_REF
          || TREE_CODE (TREE_OPERAND (exp, 0)) == ARRAY_RANGE_REF)
        goto normal;
    case CONVERT_EXPR:
      /* If we are narrowing the operand, we have to do the compare in the
         narrower mode.  */
      if ((TYPE_PRECISION (TREE_TYPE (exp))
           < TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (exp, 0)))))
        goto normal;
    case NON_LVALUE_EXPR:
    case ABS_EXPR:
    case NEGATE_EXPR:
    case LROTATE_EXPR:
    case RROTATE_EXPR:
      /* These cannot change zero->nonzero or vice versa.  */
      do_jump (TREE_OPERAND (exp, 0), if_false_label, if_true_label, prob);
      break;

    case TRUTH_NOT_EXPR:
      do_jump (TREE_OPERAND (exp, 0), if_true_label, if_false_label,
	       inv (prob));
      break;

    case COND_EXPR:
      {
	rtx_code_label *label1 = gen_label_rtx ();
	if (!if_true_label || !if_false_label)
	  {
	    drop_through_label = gen_label_rtx ();
	    if (!if_true_label)
	      if_true_label = drop_through_label;
	    if (!if_false_label)
	      if_false_label = drop_through_label;
	  }

        do_pending_stack_adjust ();
	do_jump (TREE_OPERAND (exp, 0), label1, NULL, -1);
	do_jump (TREE_OPERAND (exp, 1), if_false_label, if_true_label, prob);
        emit_label (label1);
	do_jump (TREE_OPERAND (exp, 2), if_false_label, if_true_label, prob);
	break;
      }

    case COMPOUND_EXPR:
      /* Lowered by gimplify.c.  */
      gcc_unreachable ();

    case MINUS_EXPR:
      /* Nonzero iff operands of minus differ.  */
      code = NE_EXPR;

      /* FALLTHRU */
    case EQ_EXPR:
    case NE_EXPR:
    case LT_EXPR:
    case LE_EXPR:
    case GT_EXPR:
    case GE_EXPR:
    case ORDERED_EXPR:
    case UNORDERED_EXPR:
    case UNLT_EXPR:
    case UNLE_EXPR:
    case UNGT_EXPR:
    case UNGE_EXPR:
    case UNEQ_EXPR:
    case LTGT_EXPR:
    case TRUTH_ANDIF_EXPR:
    case TRUTH_ORIF_EXPR:
    other_code:
      do_jump_1 (code, TREE_OPERAND (exp, 0), TREE_OPERAND (exp, 1),
		 if_false_label, if_true_label, prob);
      break;

    case BIT_AND_EXPR:
      /* fold_single_bit_test() converts (X & (1 << C)) into (X >> C) & 1.
	 See if the former is preferred for jump tests and restore it
	 if so.  */
      if (integer_onep (TREE_OPERAND (exp, 1)))
	{
	  tree exp0 = TREE_OPERAND (exp, 0);
	  rtx_code_label *set_label, *clr_label;
	  int setclr_prob = prob;

	  /* Strip narrowing integral type conversions.  */
	  while (CONVERT_EXPR_P (exp0)
		 && TREE_OPERAND (exp0, 0) != error_mark_node
		 && TYPE_PRECISION (TREE_TYPE (exp0))
		    <= TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (exp0, 0))))
	    exp0 = TREE_OPERAND (exp0, 0);

	  /* "exp0 ^ 1" inverts the sense of the single bit test.  */
	  if (TREE_CODE (exp0) == BIT_XOR_EXPR
	      && integer_onep (TREE_OPERAND (exp0, 1)))
	    {
	      exp0 = TREE_OPERAND (exp0, 0);
	      clr_label = if_true_label;
	      set_label = if_false_label;
	      setclr_prob = inv (prob);
	    }
	  else
	    {
	      clr_label = if_false_label;
	      set_label = if_true_label;
	    }

	  if (TREE_CODE (exp0) == RSHIFT_EXPR)
	    {
	      tree arg = TREE_OPERAND (exp0, 0);
	      tree shift = TREE_OPERAND (exp0, 1);
	      tree argtype = TREE_TYPE (arg);
	      if (TREE_CODE (shift) == INTEGER_CST
		  && compare_tree_int (shift, 0) >= 0
		  && compare_tree_int (shift, HOST_BITS_PER_WIDE_INT) < 0
		  && prefer_and_bit_test (TYPE_MODE (argtype),
					  TREE_INT_CST_LOW (shift)))
		{
		  unsigned HOST_WIDE_INT mask
		    = (unsigned HOST_WIDE_INT) 1 << TREE_INT_CST_LOW (shift);
		  do_jump (build2 (BIT_AND_EXPR, argtype, arg,
				   build_int_cstu (argtype, mask)),
			   clr_label, set_label, setclr_prob);
		  break;
		}
	    }
	}

      /* If we are AND'ing with a small constant, do this comparison in the
         smallest type that fits.  If the machine doesn't have comparisons
         that small, it will be converted back to the wider comparison.
         This helps if we are testing the sign bit of a narrower object.
         combine can't do this for us because it can't know whether a
         ZERO_EXTRACT or a compare in a smaller mode exists, but we do.  */

      if (! SLOW_BYTE_ACCESS
          && TREE_CODE (TREE_OPERAND (exp, 1)) == INTEGER_CST
          && TYPE_PRECISION (TREE_TYPE (exp)) <= HOST_BITS_PER_WIDE_INT
          && (i = tree_floor_log2 (TREE_OPERAND (exp, 1))) >= 0
          && (mode = mode_for_size (i + 1, MODE_INT, 0)) != BLKmode
          && (type = lang_hooks.types.type_for_mode (mode, 1)) != 0
          && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (exp))
          && have_insn_for (COMPARE, TYPE_MODE (type)))
        {
	  do_jump (fold_convert (type, exp), if_false_label, if_true_label,
		   prob);
          break;
        }

      if (TYPE_PRECISION (TREE_TYPE (exp)) > 1
	  || TREE_CODE (TREE_OPERAND (exp, 1)) == INTEGER_CST)
	goto normal;

      /* Boolean comparisons can be compiled as TRUTH_AND_EXPR.  */

    case TRUTH_AND_EXPR:
      /* High branch cost, expand as the bitwise AND of the conditions.
	 Do the same if the RHS has side effects, because we're effectively
	 turning a TRUTH_AND_EXPR into a TRUTH_ANDIF_EXPR.  */
      if (BRANCH_COST (optimize_insn_for_speed_p (),
		       false) >= 4
	  || TREE_SIDE_EFFECTS (TREE_OPERAND (exp, 1)))
	goto normal;
      code = TRUTH_ANDIF_EXPR;
      goto other_code;

    case BIT_IOR_EXPR:
    case TRUTH_OR_EXPR:
      /* High branch cost, expand as the bitwise OR of the conditions.
	 Do the same if the RHS has side effects, because we're effectively
	 turning a TRUTH_OR_EXPR into a TRUTH_ORIF_EXPR.  */
      if (BRANCH_COST (optimize_insn_for_speed_p (), false) >= 4
	  || TREE_SIDE_EFFECTS (TREE_OPERAND (exp, 1)))
	goto normal;
      code = TRUTH_ORIF_EXPR;
      goto other_code;

      /* Fall through and generate the normal code.  */
    default:
    normal:
      temp = expand_normal (exp);
      do_pending_stack_adjust ();
      /* The RTL optimizers prefer comparisons against pseudos.  */
      if (GET_CODE (temp) == SUBREG)
	{
	  /* Compare promoted variables in their promoted mode.  */
	  if (SUBREG_PROMOTED_VAR_P (temp)
	      && REG_P (XEXP (temp, 0)))
	    temp = XEXP (temp, 0);
	  else
	    temp = copy_to_reg (temp);
	}
      do_compare_rtx_and_jump (temp, CONST0_RTX (GET_MODE (temp)),
			       NE, TYPE_UNSIGNED (TREE_TYPE (exp)),
			       GET_MODE (temp), NULL_RTX,
			       if_false_label, if_true_label, prob);
    }

  if (drop_through_label)
    {
      do_pending_stack_adjust ();
      emit_label (drop_through_label);
    }
}
示例#8
0
int PacketHandler::player_block_placement(User *user)
{
  if(!user->buffer.haveData(12))
  {
    return PACKET_NEED_MORE_DATA;
  }
  sint8 y, direction;
  sint16 newblock;
  sint32 x, z;
  /* replacement of block */
  uint8 oldblock;
  uint8 metadata;
  /* neighbour blocks */
  uint8 block;
  uint8 meta;
  sint8 count,health;

  user->buffer >> x >> y >> z >> direction >> newblock;

  if(newblock >= 0)
  {
    if(!user->buffer.haveData(2))
    {
      return PACKET_NEED_MORE_DATA;
    }
    user->buffer >> count >> health;
  }
  user->buffer.removePacket();


  if (!Mineserver::get()->map()->getBlock(x, y, z, &oldblock, &metadata))
  {
    return PACKET_OK;
  }
  
  //Check if we need to open a window
  if(oldblock == BLOCK_CHEST)
  {
    //ToDo: check for large chest!
    Mineserver::get()->inventory()->windowOpen(user,WINDOW_CHEST,x, y, z);
    return PACKET_OK;
  }

  if(oldblock == BLOCK_FURNACE || oldblock == BLOCK_BURNING_FURNACE)
  {
    Mineserver::get()->inventory()->windowOpen(user,WINDOW_FURNACE,x, y, z);
    return PACKET_OK;
  }

  if(oldblock == BLOCK_WORKBENCH)
  {

    Mineserver::get()->inventory()->windowOpen(user,WINDOW_WORKBENCH,x, y, z);
    return PACKET_OK;
  }

  // TODO: Handle sint16 itemID's
  if(newblock > 255 && newblock != ITEM_SIGN)
  {
    return PACKET_OK;
  }

  bool foundFromInventory = false;

  #define INV_TASKBAR_START 36
  if(user->inv[INV_TASKBAR_START+user->currentItemSlot()].type == newblock && newblock != -1)
  {
    //Are we really placing this?
    user->inv[INV_TASKBAR_START+user->currentItemSlot()].count--;
    if(user->inv[INV_TASKBAR_START+user->currentItemSlot()].count == 0)
    {
      user->inv[INV_TASKBAR_START+user->currentItemSlot()] = Item();
      //ToDo: add holding change packet.
    }
    user->buffer << (sint8)PACKET_SET_SLOT << (sint8)WINDOW_PLAYER 
                 << (sint16)(INV_TASKBAR_START+user->currentItemSlot())
                 << (sint16)user->inv[INV_TASKBAR_START+user->currentItemSlot()].type;
    if(user->inv[INV_TASKBAR_START+user->currentItemSlot()].type != -1)
    {
      user->buffer << (sint8)user->inv[INV_TASKBAR_START+user->currentItemSlot()].count
                   << (sint8)user->inv[INV_TASKBAR_START+user->currentItemSlot()].health;
    }
    foundFromInventory = true;
  }
  #undef INV_TASKBAR_START


  // TODO: Handle processing of
  if(direction == -1 || !foundFromInventory)
  {
    return PACKET_OK;
  }

  // Minecart testing!!
  if(newblock == ITEM_MINECART && Mineserver::get()->map()->getBlock(x, y, z, &oldblock, &metadata))
  {
    if (oldblock != BLOCK_MINECART_TRACKS)
    {
      return PACKET_OK;
    }

    Mineserver::get()->screen()->log("Spawn minecart");
    sint32 EID=generateEID();
    Packet pkt;
    // MINECART
    pkt << PACKET_ADD_OBJECT << (sint32)EID << (sint8)10 << (sint32)(x*32+16) << (sint32)(y*32) << (sint32)(z*32+16);
    user->sendAll((uint8 *)pkt.getWrite(), pkt.getWriteLen());
  }

  if (newblock == -1 && newblock != ITEM_SIGN)
  {
     Mineserver::get()->screen()->log("ignoring: "+dtos(newblock));
     return PACKET_OK;
  }

  if(y < 0)
  {
    return PACKET_OK;
  }


#ifdef _DEBUG
  Mineserver::get()->screen()->log("Block_placement: "+dtos(newblock)+" ("+dtos(x)+","+dtos((int)y)+","+dtos(z)+") dir: "+dtos((int)direction));
#endif

  if (direction)
  {
    direction = 6-direction;
  }

  Callback callback;
  Function event;
  Function::invoker_type inv(user, newblock, x, y, z, direction);

  //if (Mineserver::get()->map()->getBlock(x, y, z, &oldblock, &metadata))
  {
    uint8 oldblocktop;
    uint8 metadatatop;
    sint8 check_y = y;
    sint32 check_x = x;
    sint32 check_z = z;

    /* client doesn't give us the correct block for lava and water, check block above */
    switch(direction)
    {
    case BLOCK_TOP:
      check_y++;
      break;
    case BLOCK_NORTH:
      check_x++;
      break;
    case BLOCK_SOUTH:
      check_x--;
      break;
    case BLOCK_EAST:
      check_z++;
      break;
    case BLOCK_WEST:
      check_z--;
      break;
    default:
      break;
    }

    if (Mineserver::get()->map()->getBlock(check_x, check_y, check_z, &oldblocktop, &metadatatop) && (oldblocktop == BLOCK_LAVA || oldblocktop == BLOCK_STATIONARY_LAVA || oldblocktop == BLOCK_WATER || oldblocktop == BLOCK_STATIONARY_WATER))
    {
      /* block above needs replacing rather then the block sent by the client */
      inv = Function::invoker_type(user, newblock, check_x, check_y, check_z, direction);
      Mineserver::get()->plugin()->runBlockCallback(oldblocktop, "onReplace", inv);
      if ((static_cast<Hook6<bool,User*,sint32,sint8,sint32,uint8,uint8>*>(Mineserver::get()->plugin()->getHook("BlockReplacePre")))->doUntilFalse(user, check_x, check_y, check_z, oldblock, newblock))
      {
        return PACKET_OK;
      }
      (static_cast<Hook6<void,User*,sint32,sint8,sint32,uint8,uint8>*>(Mineserver::get()->plugin()->getHook("BlockReplacePost")))->doAll(user, check_x, check_y, check_z, oldblock, newblock);
    }
    else
    {
      inv = Function::invoker_type(user, newblock, x, y, z, direction);
      Mineserver::get()->plugin()->runBlockCallback(oldblock, "onReplace", inv);
      if ((static_cast<Hook6<bool,User*,sint32,sint8,sint32,uint8,uint8>*>(Mineserver::get()->plugin()->getHook("BlockReplacePre")))->doUntilFalse(user, x, y, z, oldblock, newblock))
      {
        return PACKET_OK;
      }
      (static_cast<Hook6<void,User*,sint32,sint8,sint32,uint8,uint8>*>(Mineserver::get()->plugin()->getHook("BlockReplacePost")))->doAll(user, x, y, z, oldblock, newblock);
    }

    if ((static_cast<Hook5<bool,User*,sint32,sint8,sint32,uint8>*>(Mineserver::get()->plugin()->getHook("BlockPlacePre")))->doUntilFalse(user, check_x, check_y, check_z, newblock))
    {
      return PACKET_OK;
    }

    /* We pass the newblock to the newblock's onPlace callback because
    the callback doesn't know what type of block we're placing. Instead
    the callback's job is to describe the behaviour when placing the
    block down, not to place any specifically block itself. */
    inv = Function::invoker_type(user, newblock, x, y, z, direction);
    Mineserver::get()->plugin()->runBlockCallback(newblock, "onPlace", inv);

		switch(direction)
		{
			case BLOCK_BOTTOM:
				y--;
				break;
			case BLOCK_TOP:
				y++;
				break;
			case BLOCK_SOUTH:
				x--;
				break;
			case BLOCK_NORTH:
				x++;
				break;
			case BLOCK_WEST:
				z--;
				break;
			case BLOCK_EAST:
				z++;
				break;
			default:
				break;
		}
		
    (static_cast<Hook5<void,User*,sint32,sint8,sint32,uint8>*>(Mineserver::get()->plugin()->getHook("BlockPlacePost")))->doAll(user, x, y, z, newblock);

    /* notify neighbour blocks of the placed block */
    if (Mineserver::get()->map()->getBlock(x+1, y, z, &block, &meta) && block != BLOCK_AIR)
    {
      inv = Function::invoker_type(user, newblock, x+1, y, z, BLOCK_SOUTH);
      Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourPlace", inv);
      (static_cast<Hook4<void,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourPlace")))->doAll(user, x+1, y, z);
		}

    if (Mineserver::get()->map()->getBlock(x-1, y, z, &block, &meta) && block != BLOCK_AIR)
    {
      inv = Function::invoker_type(user, newblock, x-1, y, z, BLOCK_NORTH);
      Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourPlace", inv);
      (static_cast<Hook4<void,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourPlace")))->doAll(user, x-1, y, z);
		}

    if (Mineserver::get()->map()->getBlock(x, y+1, z, &block, &meta) && block != BLOCK_AIR)
    {
      inv = Function::invoker_type(user, newblock, x, y+1, z, BLOCK_TOP);
      Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourPlace", inv);
      (static_cast<Hook4<void,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourPlace")))->doAll(user, x, y+1, z);
		}

    if (Mineserver::get()->map()->getBlock(x, y-1, z, &block, &meta) && block != BLOCK_AIR)
    {
      inv = Function::invoker_type(user, newblock, x, y-1, z, BLOCK_BOTTOM);
      Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourPlace", inv);
      (static_cast<Hook4<void,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourPlace")))->doAll(user, x, y-1, z);
		}

    if (Mineserver::get()->map()->getBlock(x, y, z+1, &block, &meta) && block != BLOCK_AIR)
    {
      inv = Function::invoker_type(user, newblock, x, y, z+1, BLOCK_WEST);
      Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourPlace", inv);
      (static_cast<Hook4<void,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourPlace")))->doAll(user, x, y, z+1);
		}

    if (Mineserver::get()->map()->getBlock(x, y, z-1, &block, &meta) && block != BLOCK_AIR)
    {
      inv = Function::invoker_type(user, newblock, x, y, z-1, BLOCK_EAST);
      Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourPlace", inv);
      (static_cast<Hook4<void,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourPlace")))->doAll(user, x, y, z-1);
		}
  }
	
  /* TODO: Should be removed from here. Only needed for liquid related blocks? */
  Mineserver::get()->physics()->checkSurrounding(vec(x, y, z));
  return PACKET_OK;
}
示例#9
0
int main (int argc, char* argv[])
{
	int x = (inv(0x9) >= g_8);
	printf("%d\n", x);
	return 0;
}
示例#10
0
文件: func.c 项目: atoun/xoscope
void
inv2(Signal *sig)
{
  inv(sig, ch[1].signal);
}
示例#11
0
int PacketHandler::player_digging(User *user)
{
  sint8 status;
  sint32 x;
  sint8  y;
  sint32 z;
  sint8 direction;
  uint8 block;
  uint8 meta;

  user->buffer >> status >> x >> y >> z >> direction;

  if(!user->buffer)
  {
    return PACKET_NEED_MORE_DATA;
  }

  user->buffer.removePacket();

  if(!Mineserver::get()->map()->getBlock(x, y, z, &block, &meta))
  {
    return PACKET_OK;
  }

  Function::invoker_type inv(user, status, x, y, z, direction);

  switch(status)
  {
    case BLOCK_STATUS_STARTED_DIGGING:
    {
      (static_cast<Hook4<void,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("PlayerDiggingStarted")))->doAll(user, x, y, z);
      Mineserver::get()->plugin()->runBlockCallback(block, "onStartedDigging", inv);
      break;
    }
    case BLOCK_STATUS_DIGGING:
    {
      (static_cast<Hook4<void,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("PlayerDigging")))->doAll(user, x, y, z);
      Mineserver::get()->plugin()->runBlockCallback(block, "onDigging", inv);
      break;
    }
    case BLOCK_STATUS_STOPPED_DIGGING:
    {
      (static_cast<Hook4<void,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("PlayerDiggingStopped")))->doAll(user, x, y, z);
      Mineserver::get()->plugin()->runBlockCallback(block, "onStoppedDigging", inv);
      break;
    }
    case BLOCK_STATUS_BLOCK_BROKEN:
    {
      //Player tool usage calculation etc
      #define itemSlot (36+user->currentItemSlot())
      bool rightUse;
      sint16 itemHealth=Mineserver::get()->inventory()->itemHealth(user->inv[itemSlot].type,block,rightUse);
      if(itemHealth > 0)
      {
         user->inv[itemSlot].health++;
         if(!rightUse)
           user->inv[itemSlot].health++;
         if(itemHealth <= user->inv[itemSlot].health)
         {
            user->inv[itemSlot].count--;
            if(user->inv[itemSlot].count == 0)
            {
              user->inv[itemSlot] = Item();
            }            
         }
         Mineserver::get()->inventory()->setSlot(user,WINDOW_PLAYER,itemSlot,user->inv[itemSlot].type,
                                                 user->inv[itemSlot].count,user->inv[itemSlot].health);
      }
      #undef itemSlot

      if ((static_cast<Hook4<bool,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("BlockBreakPre")))->doUntilFalse(user, x, y, z))
      {
        return PACKET_OK;
      }

      (static_cast<Hook4<void,User*,sint32,sint8,sint32>*>(Mineserver::get()->plugin()->getHook("BlockBreakPost")))->doAll(user, x, y, z);
      Mineserver::get()->plugin()->runBlockCallback(block, "onBroken", inv);

      /* notify neighbour blocks of the broken block */
      status = block;
      if (Mineserver::get()->map()->getBlock(x+1, y, z, &block, &meta) && block != BLOCK_AIR)
      {
        (static_cast<Hook7<bool,User*,sint32,sint8,sint32, sint32, sint8, sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourBreak")))->doAll(user, x+1, y, z, x, y, z);
        inv = Function::invoker_type(user, status, x+1, y, z, BLOCK_SOUTH);
        Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourBroken", inv);
      }

      if (Mineserver::get()->map()->getBlock(x-1, y, z, &block, &meta) && block != BLOCK_AIR)
      {
        (static_cast<Hook7<bool,User*,sint32,sint8,sint32, sint32, sint8, sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourBreak")))->doAll(user, x-1, y, z, x, y, z);
        inv = Function::invoker_type(user, status, x-1, y, z, BLOCK_NORTH);
        Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourBroken", inv);
      }

      if (Mineserver::get()->map()->getBlock(x, y+1, z, &block, &meta) && block != BLOCK_AIR)
      {
        (static_cast<Hook7<bool,User*,sint32,sint8,sint32, sint32, sint8, sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourBreak")))->doAll(user, x, y+1, z, x, y, z);
        inv = Function::invoker_type(user, status, x, y+1, z, BLOCK_TOP);
        Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourBroken", inv);
      }

      if (Mineserver::get()->map()->getBlock(x, y-1, z, &block, &meta) && block != BLOCK_AIR)
      {
        (static_cast<Hook7<bool,User*,sint32,sint8,sint32, sint32, sint8, sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourBreak")))->doAll(user, x, y-1, z, x, y, z);
        inv = Function::invoker_type(user, status, x, y-1, z, BLOCK_BOTTOM);
        Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourBroken", inv);
      }

      if (Mineserver::get()->map()->getBlock(x, y, z+1, &block, &meta) && block != BLOCK_AIR)
      {
        (static_cast<Hook7<bool,User*,sint32,sint8,sint32, sint32, sint8, sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourBreak")))->doAll(user, x, y, z+1, x, y, z);
        inv = Function::invoker_type(user, status, x, y, z+1, BLOCK_WEST);
        Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourBroken", inv);
      }

      if (Mineserver::get()->map()->getBlock(x, y, z-1, &block, &meta) && block != BLOCK_AIR)
      {
        (static_cast<Hook7<bool,User*,sint32,sint8,sint32, sint32, sint8, sint32>*>(Mineserver::get()->plugin()->getHook("BlockNeighbourBreak")))->doAll(user, x, y, z-1, x, y, z);
        inv = Function::invoker_type(user, status, x, y, z-1, BLOCK_EAST);
        Mineserver::get()->plugin()->runBlockCallback(block, "onNeighbourBroken", inv);
      }

      break;
    }
    case BLOCK_STATUS_PICKUP_SPAWN:
    {
      //ToDo: handle
      #define itemSlot (36+user->currentItemSlot())
      if(user->inv[itemSlot].type > 0)
      {
        Mineserver::get()->map()->createPickupSpawn(user->pos.x, user->pos.y,user->pos.z,user->inv[itemSlot].type,1,user->inv[itemSlot].health,user);

        user->inv[itemSlot].count--;
        if(user->inv[itemSlot].count == 0)
        {
          user->inv[itemSlot] = Item();
        }
        Mineserver::get()->inventory()->setSlot(user,WINDOW_PLAYER,itemSlot,user->inv[itemSlot].type,
                                                user->inv[itemSlot].count,user->inv[itemSlot].health);
      }
      break;
      #undef itemSlot
    }
    
  }

  return PACKET_OK;
}
示例#12
0
文件: func.c 项目: atoun/xoscope
void
inv1(Signal *sig)
{
  inv(sig, ch[0].signal);
}
示例#13
0
文件: map_image.cpp 项目: jguinet/s2p
/// Apply geometric transform to image.
///
/// The transformation \a map is applied to the image \a in and the result
/// stored in \a im. If \a adjustSize is \c true, \a im will be sized so that
/// it contains all the transformed rectangle, otherwise it stays at original
/// size.
///
/// The returned pair of integers is the offset of the returned image \a im
/// with respect to original image \a in. If \a adjustSize is \c false, this is
/// (0,0), otherwise the location of upper-left corner of \a im in pixel
/// coordinates of \a in.
///
/// Interpolation is done by spline. Anti-aliasing filter is optional.
///
/// \a vOut is the background value to put at pixels outside image.
std::pair<int,int> map_image(LWImage<float> in,
                             libNumerics::Homography map,
                             LWImage<float>& im,
                             int order, bool adjustSize,
                             bool antiAlias, float vOut)
{
    int w = in.w, h = in.h;
    float zoomOut = antiAlias?
        static_cast<float>( minZoomOut(map.mat(), w, h) ): 1.0f;
    const libNumerics::Homography oriMap(map);
    const int oriW=w, oriH=h;
    std::pair<int,int> offset(0,0);
    if(adjustSize) {
        offset = boundingBox(map, w, h);
        free(im.data);
        im = alloc_image<float>(w, h, in.comps);
    }
    if(zoomOut < 1.0f) {
        float zoomIn = 1.0f / zoomOut;
        // GF: added some extra space
        int wZoom=(int)std::ceil(w*zoomIn*1.5), hZoom=(int)std::ceil(h*zoomIn*1.5);
        LWImage<float> imZoom = alloc_image<float>(wZoom,hZoom,in.comps);
        libNumerics::matrix<double> mapZ(3,3);
        mapZ = 0.0;
        mapZ(0,0) = zoomIn;
        mapZ(1,1) = zoomIn;
        mapZ(2,2) = 1.0;
        map.mat() = mapZ*map.mat();
        map_image(in, map, imZoom, order, false, false, vOut);
        float sigma = 0.8f*sqrt(zoomIn*zoomIn-1.0f);
        gauss_convol(imZoom, sigma);
        map.mat() = 0.0;
        map.mat()(0,0)=zoomOut;
        map.mat()(1,1)=zoomOut;
        map.mat()(2,2)=1.0;
        in = imZoom;
    }
    LWImage<float> tmp = alloc_image(in);
    if( prepare_spline(tmp,order) ) {
        libNumerics::Homography inv = map.inverse();
        const int stepComp = im.stepComp();
        float* out = new float[im.comps];
        float* pixOut = im.data;
        for(int i = 0; i < im.h; i++)
            for(int j = 0; j < im.w; j++) {
                double x=j+offset.first, y=i+offset.second;
                inv(x,y);
                for(int k=0; k < im.comps; k++)
                    out[k] = vOut;
                interpolate_spline(tmp, order,
                                   static_cast<float>(x+.5),
								   static_cast<float>(y+.5), out);
                for(int k=0; k < im.comps; k++)
                    pixOut[k*stepComp] = out[k];
                pixOut += im.step();
            }
        delete [] out;
    }
    free(tmp.data);
    if(zoomOut < 1.0f) {
        free(in.data); // Was allocated above
        if(! is_number(vOut)) { // Put back mask
            libNumerics::Homography inv = oriMap.inverse();
            const int stepComp = im.stepComp();
            float* pixOut = im.data;
            for(int i = 0; i < im.h; i++)
                for(int j = 0; j < im.w; j++) {
                    double x=j+offset.first, y=i+offset.second;
                    inv(x,y);
                    if(x<0 || x>=oriW || y<0 || y>=oriH)
                        for(int k=0; k < im.comps; k++)
                            pixOut[k*stepComp] = NaN;
                    pixOut += im.step();
                }
        }
    }
    return offset;
}
示例#14
0
文件: dojump.c 项目: keparo/gcc
void
do_jump_1 (enum tree_code code, tree op0, tree op1,
	   rtx if_false_label, rtx if_true_label, int prob)
{
  enum machine_mode mode;
  rtx drop_through_label = 0;

  switch (code)
    {
    case EQ_EXPR:
      {
        tree inner_type = TREE_TYPE (op0);

        gcc_assert (GET_MODE_CLASS (TYPE_MODE (inner_type))
		    != MODE_COMPLEX_FLOAT);
	gcc_assert (GET_MODE_CLASS (TYPE_MODE (inner_type))
		    != MODE_COMPLEX_INT);

        if (integer_zerop (op1))
	  do_jump (op0, if_true_label, if_false_label, inv (prob));
        else if (GET_MODE_CLASS (TYPE_MODE (inner_type)) == MODE_INT
                 && !can_compare_p (EQ, TYPE_MODE (inner_type), ccp_jump))
	  do_jump_by_parts_equality (op0, op1, if_false_label, if_true_label,
				     prob);
        else
	  do_compare_and_jump (op0, op1, EQ, EQ, if_false_label, if_true_label,
			       prob);
        break;
      }

    case NE_EXPR:
      {
        tree inner_type = TREE_TYPE (op0);

        gcc_assert (GET_MODE_CLASS (TYPE_MODE (inner_type))
		    != MODE_COMPLEX_FLOAT);
	gcc_assert (GET_MODE_CLASS (TYPE_MODE (inner_type))
		    != MODE_COMPLEX_INT);

        if (integer_zerop (op1))
	  do_jump (op0, if_false_label, if_true_label, prob);
        else if (GET_MODE_CLASS (TYPE_MODE (inner_type)) == MODE_INT
           && !can_compare_p (NE, TYPE_MODE (inner_type), ccp_jump))
	  do_jump_by_parts_equality (op0, op1, if_true_label, if_false_label,
				     inv (prob));
        else
	  do_compare_and_jump (op0, op1, NE, NE, if_false_label, if_true_label,
			       prob);
        break;
      }

    case LT_EXPR:
      mode = TYPE_MODE (TREE_TYPE (op0));
      if (GET_MODE_CLASS (mode) == MODE_INT
          && ! can_compare_p (LT, mode, ccp_jump))
	do_jump_by_parts_greater (op0, op1, 1, if_false_label, if_true_label,
				  prob);
      else
	do_compare_and_jump (op0, op1, LT, LTU, if_false_label, if_true_label,
			     prob);
      break;

    case LE_EXPR:
      mode = TYPE_MODE (TREE_TYPE (op0));
      if (GET_MODE_CLASS (mode) == MODE_INT
          && ! can_compare_p (LE, mode, ccp_jump))
	do_jump_by_parts_greater (op0, op1, 0, if_true_label, if_false_label,
				  inv (prob));
      else
	do_compare_and_jump (op0, op1, LE, LEU, if_false_label, if_true_label,
			     prob);
      break;

    case GT_EXPR:
      mode = TYPE_MODE (TREE_TYPE (op0));
      if (GET_MODE_CLASS (mode) == MODE_INT
          && ! can_compare_p (GT, mode, ccp_jump))
	do_jump_by_parts_greater (op0, op1, 0, if_false_label, if_true_label,
				  prob);
      else
	do_compare_and_jump (op0, op1, GT, GTU, if_false_label, if_true_label,
			     prob);
      break;

    case GE_EXPR:
      mode = TYPE_MODE (TREE_TYPE (op0));
      if (GET_MODE_CLASS (mode) == MODE_INT
          && ! can_compare_p (GE, mode, ccp_jump))
	do_jump_by_parts_greater (op0, op1, 1, if_true_label, if_false_label,
				  inv (prob));
      else
	do_compare_and_jump (op0, op1, GE, GEU, if_false_label, if_true_label,
			     prob);
      break;

    case ORDERED_EXPR:
      do_compare_and_jump (op0, op1, ORDERED, ORDERED,
			   if_false_label, if_true_label, prob);
      break;

    case UNORDERED_EXPR:
      do_compare_and_jump (op0, op1, UNORDERED, UNORDERED,
			   if_false_label, if_true_label, prob);
      break;

    case UNLT_EXPR:
      do_compare_and_jump (op0, op1, UNLT, UNLT, if_false_label, if_true_label,
			   prob);
      break;

    case UNLE_EXPR:
      do_compare_and_jump (op0, op1, UNLE, UNLE, if_false_label, if_true_label,
			   prob);
      break;

    case UNGT_EXPR:
      do_compare_and_jump (op0, op1, UNGT, UNGT, if_false_label, if_true_label,
			   prob);
      break;

    case UNGE_EXPR:
      do_compare_and_jump (op0, op1, UNGE, UNGE, if_false_label, if_true_label,
			   prob);
      break;

    case UNEQ_EXPR:
      do_compare_and_jump (op0, op1, UNEQ, UNEQ, if_false_label, if_true_label,
			   prob);
      break;

    case LTGT_EXPR:
      do_compare_and_jump (op0, op1, LTGT, LTGT, if_false_label, if_true_label,
			   prob);
      break;

    case TRUTH_ANDIF_EXPR:
      if (if_false_label == NULL_RTX)
        {
	  drop_through_label = gen_label_rtx ();
	  do_jump (op0, drop_through_label, NULL_RTX, prob);
	  do_jump (op1, NULL_RTX, if_true_label, prob);
	}
      else
	{
	  do_jump (op0, if_false_label, NULL_RTX, prob);
	  do_jump (op1, if_false_label, if_true_label, prob);
	}
      break;

    case TRUTH_ORIF_EXPR:
      if (if_true_label == NULL_RTX)
	{
          drop_through_label = gen_label_rtx ();
	  do_jump (op0, NULL_RTX, drop_through_label, prob);
	  do_jump (op1, if_false_label, NULL_RTX, prob);
	}
      else
	{
	  do_jump (op0, NULL_RTX, if_true_label, prob);
	  do_jump (op1, if_false_label, if_true_label, prob);
	}
      break;

    default:
      gcc_unreachable ();
    }

  if (drop_through_label)
    {
      do_pending_stack_adjust ();
      emit_label (drop_through_label);
    }
}
示例#15
0
double
wald_method::run(const snp_row &row1, const snp_row &row2, float *output)
{
    arma::mat n0 = arma::zeros<arma::mat>( 3, 3 );
    arma::mat n1 = arma::zeros<arma::mat>( 3, 3 );
    for(int i = 0; i < row1.size( ); i++)
    {
        unsigned char snp1 = row1[ i ];
        unsigned char snp2 = row2[ i ];
        if( snp1 == 3 || snp2 == 3 || m_missing[ i ] == 1 )
        {
            continue;
        }

        unsigned int pheno = m_pheno[ i ];
        if( pheno == 0 )
        {
            n0( snp1, snp2 ) += 1;
        }
        else if( pheno == 1 )
        {
            n1( snp1, snp2 ) += 1;
        }
    }

    arma::mat eta( 3, 3 );
    double num_samples = 0.0;
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            if( n0( i, j ) < METHOD_SMALLEST_CELL_SIZE_BINOMIAL || n1( i, j ) < METHOD_SMALLEST_CELL_SIZE_BINOMIAL )
            {
                continue;
            }

            eta( i, j ) = log( n1( i, j ) / n0( i, j ) );
            num_samples += n1( i, j ) + n0( i, j );
        }
    }

    /* Find valid parameters and estimate beta */
    int num_valid = 0;
    arma::uvec valid( 4 );
    m_beta = arma::zeros<arma::vec>( 4 );
    int i_map[] = { 1, 1, 2, 2 };
    int j_map[] = { 1, 2, 1, 2 };
    for(int i = 0; i < 4; i++)
    {
        int c_i = i_map[ i ];
        int c_j = j_map[ i ];
        if( n0( 0, 0 ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n0( 0, c_j ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n0( c_i, 0 ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n0( c_i, c_j) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n1( 0, 0 ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n1( 0, c_j ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n1( c_i, 0 ) >= METHOD_SMALLEST_CELL_SIZE_NORMAL &&
            n1( c_i, c_j) >= METHOD_SMALLEST_CELL_SIZE_NORMAL )
        {
            valid[ num_valid ] = i;
            m_beta[ num_valid ] = eta( 0, 0 ) - eta( 0, c_j ) - eta( c_i, 0 ) + eta( c_i, c_j );
            num_valid++;
        }
    }
    set_num_ok_samples( (size_t)num_samples );
    if( num_valid <= 0 )
    {
        return -9;
    }
    
    valid.resize( num_valid );
    m_beta.resize( num_valid );

    /* Construct covariance matrix */
    m_C = arma::zeros<arma::mat>( num_valid, num_valid );
    for(int iv = 0; iv < num_valid; iv++)
    {
        int i = valid[ iv ];
        int c_i = i_map[ i ];
        int c_j = j_map[ i ];

        for(int jv = 0; jv < num_valid; jv++)
        {
            int j = valid[ jv ];
            int o_i = i_map[ j ];
            int o_j = j_map[ j ];

            int same_row = c_i == o_i;
            int same_col = c_j == o_j;
            int in_cell = i == j;

            m_C( iv, jv ) = 1.0 / n0( 0, 0 ) + same_col / n0( 0, c_j ) + same_row / n0( c_i, 0 ) + in_cell / n0( c_i, c_j );
            m_C( iv, jv ) += 1.0 / n1( 0, 0 ) + same_col / n1( 0, c_j ) + same_row / n1( c_i, 0 ) + in_cell / n1( c_i, c_j );
        }
    }

    arma::mat Cinv( num_valid, num_valid );
    if( !inv( Cinv, m_C ) )
    {
        return -9;
    }
    
    /* Test if b != 0 with Wald test */
    double chi = dot( m_beta, Cinv * m_beta );
    output[ 0 ] = chi;
    output[ 1 ] = 1.0 - chi_square_cdf( chi, num_valid );
    output[ 2 ] = valid.n_elem;

    return output[ 1 ];
}
示例#16
0
 void Inverse::evalMX(const std::vector<MX>& arg, std::vector<MX>& res) {
   res[0] = inv(arg[0]);
 }
示例#17
0
文件: dojump.c 项目: boomeer/gcc
void
jumpifnot (tree exp, rtx_code_label *label, int prob)
{
  do_jump (exp, label, NULL, inv (prob));
}
int main()
{
    Leph::HumanoidFloatingModel model(Leph::SigmabanModel);
    model.putOnGround();

    Leph::ModelViewer viewer(1200, 900);

    //Inverse Kinematics
    Leph::InverseKinematics inv(model);
    //Declare model degrees of freedom
    inv.addDOF("right_hip_pitch");
    inv.addDOF("right_hip_roll");
    inv.addDOF("right_knee");
    inv.addDOF("right_ankle_pitch");
    inv.addDOF("right_ankle_roll");
    inv.addDOF("left_hip_pitch");
    inv.addDOF("left_hip_roll");
    inv.addDOF("left_knee");
    inv.addDOF("left_ankle_pitch");
    inv.addDOF("left_ankle_roll");
    inv.addDOF("base_x");
    inv.addDOF("base_y");
    inv.addDOF("base_z");
    //Declare degree of freefom box bounds 
    //XXX Not fully implemented
    inv.setLowerBound("left_knee", 0.0);
    inv.setLowerBound("right_knee", 0.0);

    //Declare target position
    inv.addTargetPosition("flying_foot", "right_foot_tip");
    inv.addTargetPosition("support_foot", "left_foot_tip");
    //target of center of mass
    inv.addTargetCOM();
    inv.targetCOM().z() -= 0.05;
    //Target orientation
    inv.addTargetOrientation("flying_foot", "right_foot_tip");
    inv.addTargetOrientation("support_foot", "left_foot_tip");
    
    Leph::Chrono chrono;
    double t = 0.0;
    while (viewer.update()) {
        t += 0.01;

        //Update targets
        inv.targetPosition("flying_foot").z() = 0.05+0.02*sin(t);
        inv.targetPosition("flying_foot").x() = 0.05+0.02*sin(2.0*t);
        inv.targetCOM().y() = 0.01*sin(t);
        inv.targetCOM().x() = 0.01*sin(2.0*t);

        chrono.start("InverseKinematics");
        //Compute Inverse Kinematics
        inv.run(0.0001, 100);
        chrono.stop("InverseKinematics");
        chrono.print();
        std::cout << "ERRORS" << std::endl;
        std::cout << "COM pos: " << inv.errorCOM() << std::endl;
        std::cout << "Flying foot pos: " << inv.errorPosition("flying_foot") << std::endl;
        std::cout << "Support foot pos: " << inv.errorPosition("support_foot") << std::endl;
        std::cout << "Flying foot orientation: " << inv.errorOrientation("flying_foot") << std::endl;
        std::cout << "Support foot orientation: " << inv.errorOrientation("support_foot") << std::endl;
        
        //Display
        Eigen::Vector3d pt = model.centerOfMass("origin");
        viewer.addTrackedPoint(pt);    
        Leph::ModelDraw(model, viewer);
    }

    return 0;
}
示例#19
0
文件: dojump.c 项目: boomeer/gcc
void
do_jump_1 (enum tree_code code, tree op0, tree op1,
	   rtx_code_label *if_false_label, rtx_code_label *if_true_label,
	   int prob)
{
  machine_mode mode;
  rtx_code_label *drop_through_label = 0;

  switch (code)
    {
    case EQ_EXPR:
      {
        tree inner_type = TREE_TYPE (op0);

        gcc_assert (GET_MODE_CLASS (TYPE_MODE (inner_type))
		    != MODE_COMPLEX_FLOAT);
	gcc_assert (GET_MODE_CLASS (TYPE_MODE (inner_type))
		    != MODE_COMPLEX_INT);

        if (integer_zerop (op1))
	  do_jump (op0, if_true_label, if_false_label, inv (prob));
        else if (GET_MODE_CLASS (TYPE_MODE (inner_type)) == MODE_INT
                 && !can_compare_p (EQ, TYPE_MODE (inner_type), ccp_jump))
	  do_jump_by_parts_equality (op0, op1, if_false_label, if_true_label,
				     prob);
        else
	  do_compare_and_jump (op0, op1, EQ, EQ, if_false_label, if_true_label,
			       prob);
        break;
      }

    case NE_EXPR:
      {
        tree inner_type = TREE_TYPE (op0);

        gcc_assert (GET_MODE_CLASS (TYPE_MODE (inner_type))
		    != MODE_COMPLEX_FLOAT);
	gcc_assert (GET_MODE_CLASS (TYPE_MODE (inner_type))
		    != MODE_COMPLEX_INT);

        if (integer_zerop (op1))
	  do_jump (op0, if_false_label, if_true_label, prob);
        else if (GET_MODE_CLASS (TYPE_MODE (inner_type)) == MODE_INT
           && !can_compare_p (NE, TYPE_MODE (inner_type), ccp_jump))
	  do_jump_by_parts_equality (op0, op1, if_true_label, if_false_label,
				     inv (prob));
        else
	  do_compare_and_jump (op0, op1, NE, NE, if_false_label, if_true_label,
			       prob);
        break;
      }

    case LT_EXPR:
      mode = TYPE_MODE (TREE_TYPE (op0));
      if (GET_MODE_CLASS (mode) == MODE_INT
          && ! can_compare_p (LT, mode, ccp_jump))
	do_jump_by_parts_greater (op0, op1, 1, if_false_label, if_true_label,
				  prob);
      else
	do_compare_and_jump (op0, op1, LT, LTU, if_false_label, if_true_label,
			     prob);
      break;

    case LE_EXPR:
      mode = TYPE_MODE (TREE_TYPE (op0));
      if (GET_MODE_CLASS (mode) == MODE_INT
          && ! can_compare_p (LE, mode, ccp_jump))
	do_jump_by_parts_greater (op0, op1, 0, if_true_label, if_false_label,
				  inv (prob));
      else
	do_compare_and_jump (op0, op1, LE, LEU, if_false_label, if_true_label,
			     prob);
      break;

    case GT_EXPR:
      mode = TYPE_MODE (TREE_TYPE (op0));
      if (GET_MODE_CLASS (mode) == MODE_INT
          && ! can_compare_p (GT, mode, ccp_jump))
	do_jump_by_parts_greater (op0, op1, 0, if_false_label, if_true_label,
				  prob);
      else
	do_compare_and_jump (op0, op1, GT, GTU, if_false_label, if_true_label,
			     prob);
      break;

    case GE_EXPR:
      mode = TYPE_MODE (TREE_TYPE (op0));
      if (GET_MODE_CLASS (mode) == MODE_INT
          && ! can_compare_p (GE, mode, ccp_jump))
	do_jump_by_parts_greater (op0, op1, 1, if_true_label, if_false_label,
				  inv (prob));
      else
	do_compare_and_jump (op0, op1, GE, GEU, if_false_label, if_true_label,
			     prob);
      break;

    case ORDERED_EXPR:
      do_compare_and_jump (op0, op1, ORDERED, ORDERED,
			   if_false_label, if_true_label, prob);
      break;

    case UNORDERED_EXPR:
      do_compare_and_jump (op0, op1, UNORDERED, UNORDERED,
			   if_false_label, if_true_label, prob);
      break;

    case UNLT_EXPR:
      do_compare_and_jump (op0, op1, UNLT, UNLT, if_false_label, if_true_label,
			   prob);
      break;

    case UNLE_EXPR:
      do_compare_and_jump (op0, op1, UNLE, UNLE, if_false_label, if_true_label,
			   prob);
      break;

    case UNGT_EXPR:
      do_compare_and_jump (op0, op1, UNGT, UNGT, if_false_label, if_true_label,
			   prob);
      break;

    case UNGE_EXPR:
      do_compare_and_jump (op0, op1, UNGE, UNGE, if_false_label, if_true_label,
			   prob);
      break;

    case UNEQ_EXPR:
      do_compare_and_jump (op0, op1, UNEQ, UNEQ, if_false_label, if_true_label,
			   prob);
      break;

    case LTGT_EXPR:
      do_compare_and_jump (op0, op1, LTGT, LTGT, if_false_label, if_true_label,
			   prob);
      break;

    case TRUTH_ANDIF_EXPR:
      {
        /* Spread the probability that the expression is false evenly between
           the two conditions. So the first condition is false half the total
           probability of being false. The second condition is false the other
           half of the total probability of being false, so its jump has a false
           probability of half the total, relative to the probability we
           reached it (i.e. the first condition was true).  */
        int op0_prob = -1;
        int op1_prob = -1;
        if (prob != -1)
          {
            int false_prob = inv (prob);
            int op0_false_prob = false_prob / 2;
            int op1_false_prob = GCOV_COMPUTE_SCALE ((false_prob / 2),
                                                     inv (op0_false_prob));
            /* Get the probability that each jump below is true.  */
            op0_prob = inv (op0_false_prob);
            op1_prob = inv (op1_false_prob);
          }
	if (if_false_label == NULL)
          {
            drop_through_label = gen_label_rtx ();
	    do_jump (op0, drop_through_label, NULL, op0_prob);
	    do_jump (op1, NULL, if_true_label, op1_prob);
          }
        else
          {
	    do_jump (op0, if_false_label, NULL, op0_prob);
            do_jump (op1, if_false_label, if_true_label, op1_prob);
          }
        break;
      }

    case TRUTH_ORIF_EXPR:
      {
        /* Spread the probability evenly between the two conditions. So
           the first condition has half the total probability of being true.
           The second condition has the other half of the total probability,
           so its jump has a probability of half the total, relative to
           the probability we reached it (i.e. the first condition was false).  */
        int op0_prob = -1;
        int op1_prob = -1;
        if (prob != -1)
          {
            op0_prob = prob / 2;
            op1_prob = GCOV_COMPUTE_SCALE ((prob / 2), inv (op0_prob));
	  }
	if (if_true_label == NULL)
	  {
	    drop_through_label = gen_label_rtx ();
	    do_jump (op0, NULL, drop_through_label, op0_prob);
	    do_jump (op1, if_false_label, NULL, op1_prob);
	  }
	else
	  {
	    do_jump (op0, NULL, if_true_label, op0_prob);
	    do_jump (op1, if_false_label, if_true_label, op1_prob);
	  }
        break;
      }

    default:
      gcc_unreachable ();
    }

  if (drop_through_label)
    {
      do_pending_stack_adjust ();
      emit_label (drop_through_label);
    }
}
示例#20
0
//------------------------------------------------------------------------------
void MfLowRankApproximation::initialize()
{
    double dx;
    double constValue;
    double endValue;
    double constEnd;
    double epsilon;


    dx = grid.DX;
    try {
        nOrbitals = cfg->lookup("spatialDiscretization.nSpatialOrbitals");
        constEnd = cfg->lookup("meanFieldIntegrator.lowRankApproximation.constEnd");
        constValue = cfg->lookup("meanFieldIntegrator.lowRankApproximation.constValue");
        endValue = cfg->lookup("meanFieldIntegrator.lowRankApproximation.endValue");
        epsilon = cfg->lookup("meanFieldIntegrator.lowRankApproximation.epsilon");
    } catch (const SettingNotFoundException &nfex) {
        cerr << "MfLowRankApproximation::Error reading entry from config object." << endl;
        exit(EXIT_FAILURE);
    }

    int nConst = constEnd/dx;
    int constCenter = nGrid/2;
    Vxy = zeros(nGrid, nGrid);

    for(uint p=0; p<potential.size(); p++) {
        for(int i=0; i<nGrid; i++) {
            for(int j=0; j<nGrid; j++) {
                Vxy(i, j) += potential[p]->evaluate(i, j);
            }
        }
    }

    // Using a simple discretization equal to the discretization of
    // the system.
    mat h = hExactSpatial();
//    mat h = hPiecewiseLinear();
    mat Q = eye(nGrid,nGrid);

    // Using a consant weight in the center of the potential
    // and a linear decrease from the center.
    vec g = gLinear(nGrid, constCenter, nConst, constValue, endValue);
    mat C = cMatrix(g, h, dx);

    vec lambda;
    mat eigvec;
    eig_sym(lambda, eigvec, inv(C.t())*Vxy*inv(C));
    mat Ut = C.t()*eigvec;

    mat QU = inv(Q)*Ut;

    // Sorting the eigenvalues by absoulte value and finding the number
    // of eigenvalues with abs(eigenval(i)) > epsilon
    uvec indices = sort_index(abs(lambda), 1);
    M = -1;
    for(uint m=0; m <lambda.n_rows; m++) {
        cout << abs(lambda(indices(m))) << endl;
        if(abs(lambda(indices(m))) < epsilon) {
            M = m;
            break;
        }
    }
//    cout << min(abs(lambda)) << endl;
//    cout << "hei" << endl;
//    cout << lambda << endl;
//    M = 63;
    if(M < 0) {
        cerr << "MfLowRankApproximation:: no eigenvalues < epsilon found."
             << " Try setting epsilon to a higher number" << endl;
        exit(EXIT_FAILURE);
    }
    eigenval = zeros(M);
    for(int m=0; m <M; m++) {
        eigenval(m) = lambda(indices(m));
    }

    // Calculating  the U matrix
    U = zeros(nGrid, M);
    for(int m=0; m < M; m++) {
        for(uint j=0; j<h.n_rows; j++) {
            U(j,m) = 0;
            for(uint i=0; i<h.n_cols; i++) {
                U(j,m) += h(j,i)*QU(i,indices(m));
            }
        }
    }
    cout << "MfLowRankApproximation:: Trunction of eigenvalues at M = " << M << endl;

#if 1 // For testing the low rank approximation's accuracy
    mat appV = zeros(nGrid, nGrid);
    for(int i=0; i<nGrid; i++) {
        for(int j=0; j<nGrid; j++) {
            appV(i,j) = 0;
            for(int m=0; m<M; m++) {
                appV(i,j) += eigenval(m)*U(i,m)*U(j,m);
            }
        }
    }
    mat diffV = abs(Vxy - appV);
    cout << "max_err = " << max(max(abs(Vxy - appV))) << endl;

    diffV.save("../DATA/diffV.mat");
    appV.save("../DATA/Vapp.mat");
    Vxy.save("../DATA/Vex.mat");
    cout << nGrid << endl;
//    exit(EXIT_SUCCESS);

#endif
    cout << "test" << endl;
    Vm = zeros<cx_vec>(M);
    Vqr = zeros<cx_vec>(nGrid);
}
示例#21
0
文件: dojump.c 项目: boomeer/gcc
static void
do_jump_by_parts_greater_rtx (machine_mode mode, int unsignedp, rtx op0,
			      rtx op1, rtx_code_label *if_false_label,
			      rtx_code_label *if_true_label,
			      int prob)
{
  int nwords = (GET_MODE_SIZE (mode) / UNITS_PER_WORD);
  rtx_code_label *drop_through_label = 0;
  bool drop_through_if_true = false, drop_through_if_false = false;
  enum rtx_code code = GT;
  int i;

  if (! if_true_label || ! if_false_label)
    drop_through_label = gen_label_rtx ();
  if (! if_true_label)
    {
      if_true_label = drop_through_label;
      drop_through_if_true = true;
    }
  if (! if_false_label)
    {
      if_false_label = drop_through_label;
      drop_through_if_false = true;
    }

  /* Deal with the special case 0 > x: only one comparison is necessary and
     we reverse it to avoid jumping to the drop-through label.  */
  if (op0 == const0_rtx && drop_through_if_true && !drop_through_if_false)
    {
      code = LE;
      if_true_label = if_false_label;
      if_false_label = drop_through_label;
      drop_through_if_true = false;
      drop_through_if_false = true;
    }

  /* Compare a word at a time, high order first.  */
  for (i = 0; i < nwords; i++)
    {
      rtx op0_word, op1_word;

      if (WORDS_BIG_ENDIAN)
        {
          op0_word = operand_subword_force (op0, i, mode);
          op1_word = operand_subword_force (op1, i, mode);
        }
      else
        {
          op0_word = operand_subword_force (op0, nwords - 1 - i, mode);
          op1_word = operand_subword_force (op1, nwords - 1 - i, mode);
        }

      /* All but high-order word must be compared as unsigned.  */
      do_compare_rtx_and_jump (op0_word, op1_word, code, (unsignedp || i > 0),
			       word_mode, NULL_RTX, NULL, if_true_label,
			       prob);

      /* Emit only one comparison for 0.  Do not emit the last cond jump.  */
      if (op0 == const0_rtx || i == nwords - 1)
	break;

      /* Consider lower words only if these are equal.  */
      do_compare_rtx_and_jump (op0_word, op1_word, NE, unsignedp, word_mode,
			       NULL_RTX, NULL, if_false_label, inv (prob));
    }

  if (!drop_through_if_false)
    emit_jump (if_false_label);
  if (drop_through_label)
    emit_label (drop_through_label);
}
示例#22
0
void PCM::updateCavity()
{
    //Cavities from expanded densities for SGA13 variant:
    if(fsp.pcmVariant == PCM_SGA13)
    {   ScalarField* shapeEx[2] = { &shape, &shapeVdw };
        for(int i=0; i<2; i++)
        {   ShapeFunction::expandDensity(wExpand[i], Rex[i], nCavity, nCavityEx[i]);
            ShapeFunction::compute(nCavityEx[i], *(shapeEx[i]), fsp.nc, fsp.sigma);
        }
    }
    else if(fsp.pcmVariant == PCM_CANDLE)
    {   nCavityEx[0] = fsp.Ztot * I(Sf[0] * J(nCavity));
        ShapeFunction::compute(nCavityEx[0], coulomb(Sf[0]*rhoExplicitTilde), shapeVdw,
                               fsp.nc, fsp.sigma, fsp.pCavity); //vdW cavity
        shape = I(wExpand[0] * J(shapeVdw)); //dielectric cavity
    }
    else if(isPCM_SCCS(fsp.pcmVariant))
        ShapeFunctionSCCS::compute(nCavity, shape, fsp.rhoMin, fsp.rhoMax, epsBulk);
    else //Compute directly from nCavity (which is a density product for SaLSA):
        ShapeFunction::compute(nCavity, shape, fsp.nc, fsp.sigma);

    //Compute and cache cavitation energy and gradients:
    const auto& solvent = fsp.solvents[0];
    switch(fsp.pcmVariant)
    {
    case PCM_SaLSA:
    case PCM_CANDLE:
    case PCM_SGA13:
    {   //Select relevant shape function:
        const ScalarFieldTilde sTilde = J(fsp.pcmVariant==PCM_SaLSA ? shape : shapeVdw);
        ScalarFieldTilde A_sTilde;
        //Cavitation:
        const double nlT = solvent->Nbulk * fsp.T;
        const double Gamma = log(nlT/solvent->Pvap) - 1.;
        const double Cp = 15. * (solvent->sigmaBulk/(2*solvent->Rvdw * nlT) - (1+Gamma)/6);
        const double coeff2 = 1. + Cp - 2.*Gamma;
        const double coeff3 = Gamma - 1. -2.*Cp;
        ScalarField sbar = I(wCavity*sTilde);
        Adiel["Cavitation"] = nlT * integral(sbar*(Gamma + sbar*(coeff2 + sbar*(coeff3 + sbar*Cp))));
        A_sTilde += wCavity*Idag(nlT * (Gamma + sbar*(2.*coeff2 + sbar*(3.*coeff3 + sbar*(4.*Cp)))));
        //Dispersion:
        ScalarFieldTildeArray Ntilde(Sf.size()), A_Ntilde(Sf.size()); //effective nuclear densities in spherical-averaged ansatz
        for(unsigned i=0; i<Sf.size(); i++)
            Ntilde[i] = solvent->Nbulk * (Sf[i] * sTilde);
        const double vdwScaleEff = (fsp.pcmVariant==PCM_CANDLE) ? fsp.sqrtC6eff : fsp.vdwScale;
        Adiel["Dispersion"] = e.vanDerWaals->energyAndGrad(atpos, Ntilde, atomicNumbers, vdwScaleEff, &A_Ntilde);
        A_vdwScale = Adiel["Dispersion"]/vdwScaleEff;
        for(unsigned i=0; i<Sf.size(); i++)
            if(A_Ntilde[i])
                A_sTilde += solvent->Nbulk * (Sf[i] * A_Ntilde[i]);
        //Propagate gradients to appropriate shape function:
        (fsp.pcmVariant==PCM_SaLSA ? Acavity_shape : Acavity_shapeVdw) = Jdag(A_sTilde);
        break;
    }
    case PCM_GLSSA13:
    {   VectorField Dshape = gradient(shape);
        ScalarField surfaceDensity = sqrt(lengthSquared(Dshape));
        ScalarField invSurfaceDensity = inv(surfaceDensity);
        A_tension = integral(surfaceDensity);
        Adiel["CavityTension"] = A_tension * fsp.cavityTension;
        Acavity_shape = (-fsp.cavityTension)*divergence(Dshape*invSurfaceDensity);
        break;
    }
    case PCM_LA12:
    case PCM_PRA05:
        break; //no contribution
case_PCM_SCCS_any:
        {   //Volume contribution:
            Adiel["CavityPressure"] = fsp.cavityPressure * (gInfo.detR - integral(shape));
            //Surface contribution:
            ScalarField shapePlus, shapeMinus;
            ShapeFunctionSCCS::compute(nCavity+(0.5*fsp.rhoDelta), shapePlus, fsp.rhoMin, fsp.rhoMax, epsBulk);
            ShapeFunctionSCCS::compute(nCavity-(0.5*fsp.rhoDelta), shapeMinus, fsp.rhoMin, fsp.rhoMax, epsBulk);
            ScalarField DnLength = sqrt(lengthSquared(gradient(nCavity)));
            Adiel["CavityTension"] = (fsp.cavityTension/fsp.rhoDelta) * integral(DnLength * (shapeMinus - shapePlus));
            break;
        }
    }
}
示例#23
0
int main(){
	init(); //inicializa operaciones

	int i, j, n;

	int shmid1,shmid2;
	key_t llave1,llave2;
	float *shm1;
	float *shm2;
	llave1 = 5677;
	llave2 = 5678;

	pid_t pid;
	char *argv[2];
	argv[0] = "Hijo";
	argv[1] = NULL;

	/*Creación de bloque de memoria compartida*/
	if((shmid1 = shmget(llave1, sizeof(float)*100, IPC_CREAT | 0666)) < 0)
	{
		perror("Error al obtener memoria compartida: shmget\n");
		exit(0);
	}
	if((shmid2 = shmget(llave2, sizeof(float)*100, IPC_CREAT | 0666)) < 0)
	{
		perror("Error al obtener memoria compartida: shmget\n");
		exit(0);
	}
	if((shm1 = shmat(shmid1, NULL, 0)) == (float *) -1){
		perror("Error al enlazar la memoria compartida: shmat\n");
		exit(0);
	}
	if((shm2 = shmat(shmid2, NULL, 0)) == (float *) -1){
		perror("Error al enlazar la memoria compartida: shmat\n");
		exit(0);
	}
	printf("shmid1: %d\n", shmid1);
	printf("shmid2: %d\n", shmid2);
	
	reset(0); //ponemos en 0 el semáforo
	reset(1); //ponemos en 0 el semáforo
	bloquear(0); //suma
	bloquear(1); //mult
	
	
	/*Valores de las matrices para el proceso hijo*/
	srand(time(NULL));
	for(i=0; i<100; i++){
		*(shm1+i) = rand() % 11;
	}
	for(i=0; i<100; i++){
		*(shm2+i) = rand() % 11;
	}
	
	/*Creación del proceso hijo*/
	if((pid= fork())==-1)
		printf("Error al crear el proceso hijo\n");
	if(pid == 0){
		execv(argv[0], argv);
	}
	else{	
	
		esperar(1); //esperamos operaciones
		/*Obtención de los resultados de la suma y producto*/
		Matriz mult = crear(10, 10);
		Matriz sum = crear(10, 10);
		for(i=0; i<10; i++){
			for(j=0; j<10; j++){
				n= (i*10) + j;
				mult->filas[i][j] = *(shm1+n);
				sum->filas[i][j] = *(shm2 + n);
			}
		}
		printf("Calculando inversas...\n");
		/*Matrices Inversas*/
		Matriz invMult = inv(mult);
		Matriz invSum = inv(sum);
		printf("\nMatriz inversa de la MULTIPLICACIÓN realizada por el HIJO:\n");
		printMatriz(invMult);
		printf("\nMatriz inversa de la SUMA realizada por el NIETO:\n");
		printMatriz(invSum);
		printf("\n");

		guardaMatriz(invMult, "multiplicacion.txt");
		guardaMatriz(invSum, "suma.txt");

		printf("Terminado.\n");

		exit(0);
	}
}
/* Function Definitions */
void magCali(const real_T data[6000], creal_T A_i[9], creal_T B[3])
{
  real_T D[20000];
  int32_T i;
  int32_T i0;
  real_T S[100];
  int32_T ind;
  real_T L_S22[16];
  real_T L_S22_i[16];
  real_T b_L_S22[16];
  real_T S22_i[16];
  real_T A[36];
  real_T b_S[24];
  real_T c_S[36];
  real_T norm_v1;
  static const real_T b_A[36] = { 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5,
    0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.25, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, -0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.25 };

  creal_T L[36];
  creal_T V[36];
  creal_T b_max;
  creal_T v1[6];
  real_T norm_VV2;
  creal_T b_S22_i[24];
  creal_T v2[4];
  creal_T v[100];
  creal_T Q[9];
  creal_T L_Q[9];
  creal_T L_Q_i[9];
  creal_T b_L_Q[9];
  creal_T b_v[3];
  creal_T QB[3];
  creal_T b_Q[9];
  real_T norm_VV3;
  creal_T b_L_Q_i[9];
  real_T ar;
  real_T ai;

  /*  magnetometer calibration */
  /*   */
  /*  Jungtaek Kim */
  /*  [email protected] */
  /*   */
  memset(&D[0], 0, 20000U * sizeof(real_T));
  for (i = 0; i < 2000; i++) {
    D[i] = data[i] * data[i];
    D[2000 + i] = data[2000 + i] * data[2000 + i];
    D[4000 + i] = data[4000 + i] * data[4000 + i];
    D[6000 + i] = 2.0 * data[2000 + i] * data[4000 + i];
    D[8000 + i] = 2.0 * data[i] * data[4000 + i];
    D[10000 + i] = 2.0 * data[i] * data[2000 + i];
    D[12000 + i] = 2.0 * data[i];
    D[14000 + i] = 2.0 * data[2000 + i];
    D[16000 + i] = 2.0 * data[4000 + i];
    D[18000 + i] = 1.0;
  }

  for (i0 = 0; i0 < 10; i0++) {
    for (i = 0; i < 10; i++) {
      S[i0 + 10 * i] = 0.0;
      for (ind = 0; ind < 2000; ind++) {
        S[i0 + 10 * i] += D[ind + 2000 * i0] * D[ind + 2000 * i];
      }
    }
  }

  for (i0 = 0; i0 < 4; i0++) {
    for (i = 0; i < 4; i++) {
      L_S22[i + (i0 << 2)] = S[(i + 10 * (6 + i0)) + 6];
    }
  }

  chol(L_S22);
  inv(L_S22, L_S22_i);
  for (i0 = 0; i0 < 4; i0++) {
    for (i = 0; i < 4; i++) {
      b_L_S22[i + (i0 << 2)] = L_S22[i0 + (i << 2)];
    }
  }

  inv(b_L_S22, L_S22);
  for (i0 = 0; i0 < 4; i0++) {
    for (i = 0; i < 4; i++) {
      S22_i[i0 + (i << 2)] = 0.0;
      for (ind = 0; ind < 4; ind++) {
        S22_i[i0 + (i << 2)] += L_S22[i0 + (ind << 2)] * L_S22_i[ind + (i << 2)];
      }
    }
  }

  /*      S22_i = pinv(S22);%I4\S22; */
  for (i0 = 0; i0 < 6; i0++) {
    for (i = 0; i < 4; i++) {
      b_S[i0 + 6 * i] = 0.0;
      for (ind = 0; ind < 4; ind++) {
        b_S[i0 + 6 * i] += S[i0 + 10 * (6 + ind)] * S22_i[ind + (i << 2)];
      }
    }
  }

  for (i0 = 0; i0 < 6; i0++) {
    for (i = 0; i < 6; i++) {
      norm_v1 = 0.0;
      for (ind = 0; ind < 4; ind++) {
        norm_v1 += b_S[i0 + 6 * ind] * S[(ind + 10 * i) + 6];
      }

      c_S[i0 + 6 * i] = S[i0 + 10 * i] - norm_v1;
    }
  }

  for (i0 = 0; i0 < 6; i0++) {
    for (i = 0; i < 6; i++) {
      A[i0 + 6 * i] = 0.0;
      for (ind = 0; ind < 6; ind++) {
        A[i0 + 6 * i] += b_A[i0 + 6 * ind] * c_S[ind + 6 * i];
      }
    }
  }

  eig(A, V, L);
  b_max = L[0];
  ind = 0;
  for (i = 0; i < 6; i++) {
    if (b_max.re < L[i + 6 * i].re) {
      b_max = L[i + 6 * i];
      ind = i;
    }
  }

  memcpy(&v1[0], &V[6 * ind], 6U * sizeof(creal_T));
  if (V[6 * ind].re < 0.0) {
    for (i0 = 0; i0 < 6; i0++) {
      v1[i0].re = -V[i0 + 6 * ind].re;
      v1[i0].im = -V[i0 + 6 * ind].im;
    }
  }

  norm_v1 = norm(v1);
  for (i0 = 0; i0 < 6; i0++) {
    norm_VV2 = v1[i0].im;
    if (v1[i0].im == 0.0) {
      v1[i0].re /= norm_v1;
      v1[i0].im = 0.0;
    } else if (v1[i0].re == 0.0) {
      v1[i0].re = 0.0;
      v1[i0].im = norm_VV2 / norm_v1;
    } else {
      v1[i0].re /= norm_v1;
      v1[i0].im = norm_VV2 / norm_v1;
    }
  }

  for (i0 = 0; i0 < 4; i0++) {
    for (i = 0; i < 6; i++) {
      norm_v1 = 0.0;
      for (ind = 0; ind < 4; ind++) {
        norm_v1 += S22_i[i0 + (ind << 2)] * S[(ind + 10 * i) + 6];
      }

      b_S22_i[i0 + (i << 2)].re = norm_v1;
      b_S22_i[i0 + (i << 2)].im = 0.0;
    }
  }

  for (i0 = 0; i0 < 4; i0++) {
    v2[i0].re = 0.0;
    v2[i0].im = 0.0;
    for (i = 0; i < 6; i++) {
      v2[i0].re += b_S22_i[i0 + (i << 2)].re * v1[i].re - 0.0 * v1[i].im;
      v2[i0].im += b_S22_i[i0 + (i << 2)].re * v1[i].im + 0.0 * v1[i].re;
    }
  }

  for (i0 = 0; i0 < 100; i0++) {
    v[i0].re = 0.0;
    v[i0].im = 0.0;
  }

  v[0] = v1[0];
  v[1] = v1[1];
  v[2] = v1[2];
  v[3] = v1[3];
  v[4] = v1[4];
  v[5] = v1[5];
  v[6].re = -v2[0].re;
  v[6].im = -v2[0].im;
  v[7].re = -v2[1].re;
  v[7].im = -v2[1].im;
  v[8].re = -v2[2].re;
  v[8].im = -v2[2].im;
  v[9].re = -v2[3].re;
  v[9].im = -v2[3].im;
  Q[0] = v[0];
  Q[3] = v[5];
  Q[6] = v[4];
  Q[1] = v[5];
  Q[4] = v[1];
  Q[7] = v[3];
  Q[2] = v[4];
  Q[5] = v[3];
  Q[8] = v[2];
  memcpy(&L_Q[0], &Q[0], 9U * sizeof(creal_T));
  b_chol(L_Q);
  b_inv(L_Q, L_Q_i);
  for (i0 = 0; i0 < 3; i0++) {
    for (i = 0; i < 3; i++) {
      b_L_Q[i + 3 * i0].re = L_Q[i0 + 3 * i].re;
      b_L_Q[i + 3 * i0].im = -L_Q[i0 + 3 * i].im;
    }
  }

  b_inv(b_L_Q, L_Q);

  /*      Q_i = pinv(Q);%I3\Q; */
  for (i0 = 0; i0 < 3; i0++) {
    for (i = 0; i < 3; i++) {
      b_L_Q[i0 + 3 * i].re = 0.0;
      b_L_Q[i0 + 3 * i].im = 0.0;
      for (ind = 0; ind < 3; ind++) {
        b_L_Q[i0 + 3 * i].re += L_Q[i0 + 3 * ind].re * L_Q_i[ind + 3 * i].re -
          L_Q[i0 + 3 * ind].im * L_Q_i[ind + 3 * i].im;
        b_L_Q[i0 + 3 * i].im += L_Q[i0 + 3 * ind].re * L_Q_i[ind + 3 * i].im +
          L_Q[i0 + 3 * ind].im * L_Q_i[ind + 3 * i].re;
      }
    }
  }

  b_v[0] = v[6];
  b_v[1] = v[7];
  b_v[2] = v[8];
  for (i0 = 0; i0 < 3; i0++) {
    norm_v1 = 0.0;
    norm_VV2 = 0.0;
    for (i = 0; i < 3; i++) {
      norm_v1 += b_L_Q[i0 + 3 * i].re * b_v[i].re - b_L_Q[i0 + 3 * i].im * b_v[i]
        .im;
      norm_VV2 += b_L_Q[i0 + 3 * i].re * b_v[i].im + b_L_Q[i0 + 3 * i].im *
        b_v[i].re;
    }

    B[i0].re = -norm_v1;
    B[i0].im = -norm_VV2;
  }

  for (i0 = 0; i0 < 3; i0++) {
    QB[i0].re = 0.0;
    QB[i0].im = 0.0;
    for (i = 0; i < 3; i++) {
      QB[i0].re += Q[i0 + 3 * i].re * B[i].re - Q[i0 + 3 * i].im * B[i].im;
      QB[i0].im += Q[i0 + 3 * i].re * B[i].im + Q[i0 + 3 * i].im * B[i].re;
    }

    b_v[i0].re = B[i0].re;
    b_v[i0].im = -B[i0].im;
  }

  b_max.re = 0.0;
  b_max.im = 0.0;
  for (i = 0; i < 3; i++) {
    b_max.re += b_v[i].re * QB[i].re - b_v[i].im * QB[i].im;
    b_max.im += b_v[i].re * QB[i].im + b_v[i].im * QB[i].re;
  }

  b_max.re -= v[9].re;
  b_max.im -= v[9].im;
  b_sqrt(&b_max);
  memcpy(&b_Q[0], &Q[0], 9U * sizeof(creal_T));
  b_eig(b_Q, L_Q, Q);
  norm_v1 = b_norm(*(creal_T (*)[3])&L_Q[0]);
  norm_VV2 = b_norm(*(creal_T (*)[3])&L_Q[3]);
  norm_VV3 = b_norm(*(creal_T (*)[3])&L_Q[6]);
  for (i0 = 0; i0 < 3; i0++) {
    if (L_Q[i0].im == 0.0) {
      L_Q_i[i0].re = L_Q[i0].re / norm_v1;
      L_Q_i[i0].im = 0.0;
    } else if (L_Q[i0].re == 0.0) {
      L_Q_i[i0].re = 0.0;
      L_Q_i[i0].im = L_Q[i0].im / norm_v1;
    } else {
      L_Q_i[i0].re = L_Q[i0].re / norm_v1;
      L_Q_i[i0].im = L_Q[i0].im / norm_v1;
    }

    if (L_Q[3 + i0].im == 0.0) {
      L_Q_i[3 + i0].re = L_Q[3 + i0].re / norm_VV2;
      L_Q_i[3 + i0].im = 0.0;
    } else if (L_Q[3 + i0].re == 0.0) {
      L_Q_i[3 + i0].re = 0.0;
      L_Q_i[3 + i0].im = L_Q[3 + i0].im / norm_VV2;
    } else {
      L_Q_i[3 + i0].re = L_Q[3 + i0].re / norm_VV2;
      L_Q_i[3 + i0].im = L_Q[3 + i0].im / norm_VV2;
    }

    if (L_Q[6 + i0].im == 0.0) {
      L_Q_i[6 + i0].re = L_Q[6 + i0].re / norm_VV3;
      L_Q_i[6 + i0].im = 0.0;
    } else if (L_Q[6 + i0].re == 0.0) {
      L_Q_i[6 + i0].re = 0.0;
      L_Q_i[6 + i0].im = L_Q[6 + i0].im / norm_VV3;
    } else {
      L_Q_i[6 + i0].re = L_Q[6 + i0].re / norm_VV3;
      L_Q_i[6 + i0].im = L_Q[6 + i0].im / norm_VV3;
    }

    for (i = 0; i < 3; i++) {
      b_L_Q[i0 + 3 * i].re = 0.0;
      b_L_Q[i0 + 3 * i].im = 0.0;
      for (ind = 0; ind < 3; ind++) {
        b_L_Q[i0 + 3 * i].re += L_Q_i[i0 + 3 * ind].re * Q[ind + 3 * i].re -
          L_Q_i[i0 + 3 * ind].im * Q[ind + 3 * i].im;
        b_L_Q[i0 + 3 * i].im += L_Q_i[i0 + 3 * ind].re * Q[ind + 3 * i].im +
          L_Q_i[i0 + 3 * ind].im * Q[ind + 3 * i].re;
      }
    }
  }

  for (i0 = 0; i0 < 3; i0++) {
    for (i = 0; i < 3; i++) {
      b_L_Q_i[i0 + 3 * i].re = 0.0;
      b_L_Q_i[i0 + 3 * i].im = 0.0;
      for (ind = 0; ind < 3; ind++) {
        b_L_Q_i[i0 + 3 * i].re += b_L_Q[i0 + 3 * ind].re * L_Q_i[i + 3 * ind].re
          - b_L_Q[i0 + 3 * ind].im * -L_Q_i[i + 3 * ind].im;
        b_L_Q_i[i0 + 3 * i].im += b_L_Q[i0 + 3 * ind].re * -L_Q_i[i + 3 * ind].
          im + b_L_Q[i0 + 3 * ind].im * L_Q_i[i + 3 * ind].re;
      }
    }
  }

  for (i0 = 0; i0 < 3; i0++) {
    for (i = 0; i < 3; i++) {
      ar = b_L_Q_i[i + 3 * i0].re * 0.569;
      ai = b_L_Q_i[i + 3 * i0].im * 0.569;
      if (b_max.im == 0.0) {
        if (ai == 0.0) {
          A_i[i + 3 * i0].re = ar / b_max.re;
          A_i[i + 3 * i0].im = 0.0;
        } else if (ar == 0.0) {
          A_i[i + 3 * i0].re = 0.0;
          A_i[i + 3 * i0].im = ai / b_max.re;
        } else {
          A_i[i + 3 * i0].re = ar / b_max.re;
          A_i[i + 3 * i0].im = ai / b_max.re;
        }
      } else if (b_max.re == 0.0) {
        if (ar == 0.0) {
          A_i[i + 3 * i0].re = ai / b_max.im;
          A_i[i + 3 * i0].im = 0.0;
        } else if (ai == 0.0) {
          A_i[i + 3 * i0].re = 0.0;
          A_i[i + 3 * i0].im = -(ar / b_max.im);
        } else {
          A_i[i + 3 * i0].re = ai / b_max.im;
          A_i[i + 3 * i0].im = -(ar / b_max.im);
        }
      } else {
        norm_VV3 = fabs(b_max.re);
        norm_v1 = fabs(b_max.im);
        if (norm_VV3 > norm_v1) {
          norm_v1 = b_max.im / b_max.re;
          norm_VV2 = b_max.re + norm_v1 * b_max.im;
          A_i[i + 3 * i0].re = (ar + norm_v1 * ai) / norm_VV2;
          A_i[i + 3 * i0].im = (ai - norm_v1 * ar) / norm_VV2;
        } else if (norm_v1 == norm_VV3) {
          norm_v1 = b_max.re > 0.0 ? 0.5 : -0.5;
          norm_VV2 = b_max.im > 0.0 ? 0.5 : -0.5;
          A_i[i + 3 * i0].re = (ar * norm_v1 + ai * norm_VV2) / norm_VV3;
          A_i[i + 3 * i0].im = (ai * norm_v1 - ar * norm_VV2) / norm_VV3;
        } else {
          norm_v1 = b_max.re / b_max.im;
          norm_VV2 = b_max.im + norm_v1 * b_max.re;
          A_i[i + 3 * i0].re = (norm_v1 * ar + ai) / norm_VV2;
          A_i[i + 3 * i0].im = (norm_v1 * ai - ar) / norm_VV2;
        }
      }
    }
  }
}
示例#25
0
文件: SVD.C 项目: Kiiree/OpenFOAM-dev
Foam::SVD::SVD(const scalarRectangularMatrix& A, const scalar minCondition)
:
    U_(A),
    V_(A.m(), A.m()),
    S_(A.m()),
    VSinvUt_(A.m(), A.n()),
    nZeros_(0)
{
    // SVDcomp to find U_, V_ and S_ - the singular values

    const label Um = U_.m();
    const label Un = U_.n();

    scalarList rv1(Um);
    scalar g = 0;
    scalar scale = 0;
    scalar s = 0;
    scalar anorm = 0;
    label l = 0;

    for (label i = 0; i < Um; i++)
    {
        l = i+2;
        rv1[i] = scale*g;
        g = s = scale = 0;

        if (i < Un)
        {
            for (label k = i; k < Un; k++)
            {
                scale += mag(U_[k][i]);
            }

            if (scale != 0)
            {
                for (label k = i; k < Un; k++)
                {
                    U_[k][i] /= scale;
                    s += U_[k][i]*U_[k][i];
                }

                scalar f = U_[i][i];
                g = -sign(Foam::sqrt(s), f);
                scalar h = f*g - s;
                U_[i][i] = f - g;

                for (label j = l-1; j < Um; j++)
                {
                    s = 0;
                    for (label k = i; k < Un; k++)
                    {
                        s += U_[k][i]*U_[k][j];
                    }

                    f = s/h;
                    for (label k = i; k < A.n(); k++)
                    {
                        U_[k][j] += f*U_[k][i];
                    }
                }

                for (label k = i; k < Un; k++)
                {
                    U_[k][i] *= scale;
                }
            }
        }

        S_[i] = scale*g;

        g = s = scale = 0;

        if (i+1 <= Un && i != Um)
        {
            for (label k = l-1; k < Um; k++)
            {
                scale += mag(U_[i][k]);
            }

            if (scale != 0)
            {
                for (label k=l-1; k < Um; k++)
                {
                    U_[i][k] /= scale;
                    s += U_[i][k]*U_[i][k];
                }

                scalar f = U_[i][l-1];
                g = -sign(Foam::sqrt(s),f);
                scalar h = f*g - s;
                U_[i][l-1] = f - g;

                for (label k = l-1; k < Um; k++)
                {
                    rv1[k] = U_[i][k]/h;
                }

                for (label j = l-1; j < Un; j++)
                {
                    s = 0;
                    for (label k = l-1; k < Um; k++)
                    {
                        s += U_[j][k]*U_[i][k];
                    }

                    for (label k = l-1; k < Um; k++)
                    {
                        U_[j][k] += s*rv1[k];
                    }
                }
                for (label k = l-1; k < Um; k++)
                {
                    U_[i][k] *= scale;
                }
            }
        }

        anorm = max(anorm, mag(S_[i]) + mag(rv1[i]));
    }

    for (label i = Um-1; i >= 0; i--)
    {
        if (i < Um-1)
        {
            if (g != 0)
            {
                for (label j = l; j < Um; j++)
                {
                    V_[j][i] = (U_[i][j]/U_[i][l])/g;
                }

                for (label j=l; j < Um; j++)
                {
                    s = 0;
                    for (label k = l; k < Um; k++)
                    {
                        s += U_[i][k]*V_[k][j];
                    }

                    for (label k = l; k < Um; k++)
                    {
                        V_[k][j] += s*V_[k][i];
                    }
                }
            }

            for (label j = l; j < Um;j++)
            {
                V_[i][j] = V_[j][i] = 0.0;
            }
        }

        V_[i][i] = 1;
        g = rv1[i];
        l = i;
    }

    for (label i = min(Um, Un) - 1; i >= 0; i--)
    {
        l = i+1;
        g = S_[i];

        for (label j = l; j < Um; j++)
        {
            U_[i][j] = 0.0;
        }

        if (g != 0)
        {
            g = 1.0/g;

            for (label j = l; j < Um; j++)
            {
                s = 0;
                for (label k = l; k < Un; k++)
                {
                    s += U_[k][i]*U_[k][j];
                }

                scalar f = (s/U_[i][i])*g;

                for (label k = i; k < Un; k++)
                {
                    U_[k][j] += f*U_[k][i];
                }
            }

            for (label j = i; j < Un; j++)
            {
                U_[j][i] *= g;
            }
        }
        else
        {
            for (label j = i; j < Un; j++)
            {
                U_[j][i] = 0.0;
            }
        }

        ++U_[i][i];
    }

    for (label k = Um-1; k >= 0; k--)
    {
        for (label its = 0; its < 35; its++)
        {
            bool flag = true;

            label nm;
            for (l = k; l >= 0; l--)
            {
                nm = l-1;
                if (mag(rv1[l]) + anorm == anorm)
                {
                    flag = false;
                    break;
                }
                if (mag(S_[nm]) + anorm == anorm) break;
            }

            if (flag)
            {
                scalar c = 0.0;
                s = 1.0;
                for (label i = l; i < k+1; i++)
                {
                    scalar f = s*rv1[i];
                    rv1[i] = c*rv1[i];

                    if (mag(f) + anorm == anorm) break;

                    g = S_[i];
                    scalar h = sqrtSumSqr(f, g);
                    S_[i] = h;
                    h = 1.0/h;
                    c = g*h;
                    s = -f*h;

                    for (label j = 0; j < Un; j++)
                    {
                        scalar y = U_[j][nm];
                        scalar z = U_[j][i];
                        U_[j][nm] = y*c + z*s;
                        U_[j][i] = z*c - y*s;
                    }
                }
            }

            scalar z = S_[k];

            if (l == k)
            {
                if (z < 0.0)
                {
                    S_[k] = -z;

                    for (label j = 0; j < Um; j++) V_[j][k] = -V_[j][k];
                }
                break;
            }
            if (its == 34)
            {
                WarningInFunction
                    << "no convergence in 35 SVD iterations"
                    << endl;
            }

            scalar x = S_[l];
            nm = k-1;
            scalar y = S_[nm];
            g = rv1[nm];
            scalar h = rv1[k];
            scalar f = ((y - z)*(y + z) + (g - h)*(g + h))/(2.0*h*y);
            g = sqrtSumSqr(f, scalar(1));
            f = ((x - z)*(x + z) + h*((y/(f + sign(g, f))) - h))/x;
            scalar c = 1.0;
            s = 1.0;

            for (label j = l; j <= nm; j++)
            {
                label i = j + 1;
                g = rv1[i];
                y = S_[i];
                h = s*g;
                g = c*g;
                scalar z = sqrtSumSqr(f, h);
                rv1[j] = z;
                c = f/z;
                s = h/z;
                f = x*c + g*s;
                g = g*c - x*s;
                h = y*s;
                y *= c;

                for (label jj = 0; jj < Um; jj++)
                {
                    x = V_[jj][j];
                    z = V_[jj][i];
                    V_[jj][j] = x*c + z*s;
                    V_[jj][i] = z*c - x*s;
                }

                z = sqrtSumSqr(f, h);
                S_[j] = z;
                if (z)
                {
                    z = 1.0/z;
                    c = f*z;
                    s = h*z;
                }
                f = c*g + s*y;
                x = c*y - s*g;

                for (label jj=0; jj < Un; jj++)
                {
                    y = U_[jj][j];
                    z = U_[jj][i];
                    U_[jj][j] = y*c + z*s;
                    U_[jj][i] = z*c - y*s;
                }
            }
            rv1[l] = 0.0;
            rv1[k] = f;
            S_[k] = x;
        }
    }

    // zero singular values that are less than minCondition*maxS
    const scalar minS = minCondition*S_[findMax(S_)];
    forAll(S_, i)
    {
        if (S_[i] <= minS)
        {
            //Info<< "Removing " << S_[i] << " < " << minS << endl;
            S_[i] = 0;
            nZeros_++;
        }
    }

    // now multiply out to find the pseudo inverse of A, VSinvUt_
    multiply(VSinvUt_, V_, inv(S_), U_.T());

    // test SVD
    /*scalarRectangularMatrix SVDA(A.n(), A.m());
    multiply(SVDA, U_, S_, transpose(V_));
    scalar maxDiff = 0;
    scalar diff = 0;
    for (label i = 0; i < A.n(); i++)
    {
        for (label j = 0; j < A.m(); j++)
        {
            diff = mag(A[i][j] - SVDA[i][j]);
            if (diff > maxDiff) maxDiff = diff;
        }
    }
    Info<< "Maximum discrepancy between A and svd(A) = " << maxDiff << endl;

    if (maxDiff > 4)
    {
        Info<< "singular values " << S_ << endl;
    }
    */
}
示例#26
0
UniValue sendrawtransaction(const JSONRPCRequest& request)
{
    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
        throw std::runtime_error(
            "sendrawtransaction \"hexstring\" ( allowhighfees )\n"
            "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
            "\nAlso see createrawtransaction and signrawtransaction calls.\n"
            "\nArguments:\n"
            "1. \"hexstring\"    (string, required) The hex string of the raw transaction)\n"
            "2. allowhighfees    (boolean, optional, default=false) Allow high fees\n"
            "\nResult:\n"
            "\"hex\"             (string) The transaction hash in hex\n"
            "\nExamples:\n"
            "\nCreate a transaction\n"
            + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
            "Sign the transaction, and get back the hex\n"
            + HelpExampleCli("signrawtransaction", "\"myhex\"") +
            "\nSend the transaction (signed hex)\n"
            + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
            "\nAs a json rpc call\n"
            + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
        );

    ObserveSafeMode();
    LOCK(cs_main);
    RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});

    // parse hex string from parameter
    CMutableTransaction mtx;
    if (!DecodeHexTx(mtx, request.params[0].get_str()))
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
    CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
    const uint256& hashTx = tx->GetHash();

    CAmount nMaxRawTxFee = maxTxFee;
    if (!request.params[1].isNull() && request.params[1].get_bool())
        nMaxRawTxFee = 0;

    CCoinsViewCache &view = *pcoinsTip;
    bool fHaveChain = false;
    for (size_t o = 0; !fHaveChain && o < tx->vout.size(); o++) {
        const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
        fHaveChain = !existingCoin.IsSpent();
    }
    bool fHaveMempool = mempool.exists(hashTx);
    if (!fHaveMempool && !fHaveChain) {
        // push to local node and sync with wallets
        CValidationState state;
        bool fMissingInputs;
        bool fLimitFree = true;
        if (!AcceptToMemoryPool(mempool, state, std::move(tx), fLimitFree, &fMissingInputs, nullptr, false, nMaxRawTxFee)) {
            if (state.IsInvalid()) {
                throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
            } else {
                if (fMissingInputs) {
                    throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
                }
                throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
            }
        }
    } else if (fHaveChain) {
        throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
    }
    if(!g_connman)
        throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");

    CInv inv(MSG_TX, hashTx);
    g_connman->ForEachNode([&inv](CNode* pnode)
    {
        pnode->PushInventory(inv);
    });
    return hashTx.GetHex();
}
示例#27
0
void inv(mat_ZZ_pE& X, const mat_ZZ_pE& A)
{
   ZZ_pE d;
   inv(d, X, A);
   if (d == 0) ArithmeticError("inv: non-invertible matrix");
}
示例#28
0
void inv(mat_GF2& X, const mat_GF2& A)
{
   GF2 d;
   inv(d, X, A);
   if (d == 0) Error("inv: non-invertible matrix");
}
示例#29
0
文件: df12fun.cpp 项目: pwoo/admb
/**
 * Description not yet available.
 * \param
 */
  df1_two_variable operator / (const df1_two_variable& x,
    const df1_two_variable& y)
  {
    df1_two_variable u=inv(y);
    return x*u;
  }
void ElectronScattering::dump(const Everything& everything)
{	Everything& e = (Everything&)everything; //may modify everything to save memory / optimize
	this->e = &everything;
	nBands = e.eInfo.nBands;
	nSpinor = e.eInfo.spinorLength();
	
	logPrintf("\n----- Electron-electron scattering Im(Sigma) -----\n"); logFlush();

	//Update default parameters:
	if(!eta)
	{	eta = e.eInfo.kT;
		if(!eta) die("eta must be specified explicitly since electronic temperature is zero.\n");
	}
	if(!Ecut) Ecut = e.cntrl.Ecut;
	double oMin = DBL_MAX, oMax = -DBL_MAX; //occupied energy range
	double uMin = DBL_MAX, uMax = -DBL_MAX; //unoccupied energy range
	for(int q=e.eInfo.qStart; q<e.eInfo.qStop; q++)
		for(int b=0; b<nBands; b++)
		{	double E = e.eVars.Hsub_eigs[q][b];
			double f = e.eVars.F[q][b];
			if(f > fCut) //sufficiently occupied
			{	oMin = std::min(oMin, E);
				oMax = std::max(oMax, E);
			}
			if(f < 1.-fCut) //sufficiently unoccupied
			{	uMin = std::min(uMin, E);
				uMax = std::max(uMax, E);
			}
		}
	mpiUtil->allReduce(oMin, MPIUtil::ReduceMin);
	mpiUtil->allReduce(oMax, MPIUtil::ReduceMax);
	mpiUtil->allReduce(uMin, MPIUtil::ReduceMin);
	mpiUtil->allReduce(uMax, MPIUtil::ReduceMax);
	if(!omegaMax) omegaMax = std::max(uMax-uMin, oMax-oMin);
	Emin = uMin - omegaMax;
	Emax = oMax + omegaMax;
	//--- print selected values after fixing defaults:
	logPrintf("Frequency resolution:    %lg\n", eta);
	logPrintf("Dielectric matrix Ecut:  %lg\n", Ecut);
	logPrintf("Maximum energy transfer: %lg\n", omegaMax);
	
	//Initialize frequency grid:
	diagMatrix omegaGrid, wOmega;
	omegaGrid.push_back(0.);
	wOmega.push_back(0.5*eta); //integration weight (halved at endpoint)
	while(omegaGrid.back()<omegaMax + 10*eta) //add margin for covering enough of the Lorentzians
	{	omegaGrid.push_back(omegaGrid.back() + eta);
		wOmega.push_back(eta);
	}
	int iOmegaStart, iOmegaStop; //split dielectric computation over frequency grid
	TaskDivision omegaDiv(omegaGrid.size(), mpiUtil);
	omegaDiv.myRange(iOmegaStart, iOmegaStop);
	logPrintf("Initialized frequency grid with resolution %lg and %d points.\n", eta, omegaGrid.nRows());

	//Make necessary quantities available on all processes:
	C.resize(e.eInfo.nStates);
	E.resize(e.eInfo.nStates);
	F.resize(e.eInfo.nStates);
	for(int q=0; q<e.eInfo.nStates; q++)
	{	int procSrc = e.eInfo.whose(q);
		if(procSrc == mpiUtil->iProcess())
		{	std::swap(C[q], e.eVars.C[q]);
			std::swap(E[q], e.eVars.Hsub_eigs[q]);
			std::swap(F[q], e.eVars.F[q]);
		}
		else
		{	C[q].init(nBands, e.basis[q].nbasis * nSpinor, &e.basis[q], &e.eInfo.qnums[q]);
			E[q].resize(nBands);
			F[q].resize(nBands);
		}
		C[q].bcast(procSrc);
		E[q].bcast(procSrc);
		F[q].bcast(procSrc);
	}
	
	//Randomize supercell to improve load balancing on k-mesh:
	{	std::vector< vector3<> >& kmesh = e.coulombParams.supercell->kmesh;
		std::vector<Supercell::KmeshTransform>& kmeshTransform = e.coulombParams.supercell->kmeshTransform;
		for(size_t ik=0; ik<kmesh.size()-1; ik++)
		{	size_t jk = ik + floor(Random::uniform(kmesh.size()-ik));
			mpiUtil->bcast(jk);
			if(jk !=ik && jk < kmesh.size())
			{	std::swap(kmesh[ik], kmesh[jk]);
				std::swap(kmeshTransform[ik], kmeshTransform[jk]);
			}
		}
	}
	
	//Report maximum nearest-neighbour eigenvalue change (to guide choice of eta)
	supercell = e.coulombParams.supercell;
	matrix3<> kBasisT = inv(supercell->Rsuper) * e.gInfo.R;
	vector3<> kBasis[3]; for(int j=0; j<3; j++) kBasis[j] = kBasisT.row(j);
	plook = std::make_shared< PeriodicLookup< vector3<> > >(supercell->kmesh, e.gInfo.GGT);
	size_t ikStart, ikStop;
	TaskDivision(supercell->kmesh.size(), mpiUtil).myRange(ikStart, ikStop);
	double dEmax = 0.;
	for(size_t ik=ikStart; ik<ikStop; ik++)
	{	const diagMatrix& Ei = E[supercell->kmeshTransform[ik].iReduced];
		for(int j=0; j<3; j++)
		{	size_t jk = plook->find(supercell->kmesh[ik] + kBasis[j]);
			myassert(jk != string::npos);
			const diagMatrix& Ej = E[supercell->kmeshTransform[jk].iReduced];
			for(int b=0; b<nBands; b++)
				if(Emin <= Ei[b] && Ei[b] <= Emax)
					dEmax = std::max(dEmax, fabs(Ej[b]-Ei[b]));
		}
	}
	mpiUtil->allReduce(dEmax, MPIUtil::ReduceMax);
	logPrintf("Maximum k-neighbour dE: %lg (guide for selecting eta)\n", dEmax);
	
	//Initialize reduced q-Mesh:
	//--- q-mesh is a k-point dfference mesh, which could differ from k-mesh for off-Gamma meshes
	qmesh.resize(supercell->kmesh.size());
	for(size_t iq=0; iq<qmesh.size(); iq++)
	{	qmesh[iq].k = supercell->kmesh[iq] - supercell->kmesh[0]; //k-difference
		qmesh[iq].weight = 1./qmesh.size(); //uniform mesh
		qmesh[iq].spin = 0;
	}
	logPrintf("Symmetries reduced momentum transfers (q-mesh) from %d to ", int(qmesh.size()));
	qmesh = e.symm.reduceKmesh(qmesh);
	logPrintf("%d entries\n", int(qmesh.size())); logFlush();
	
	//Initialize polarizability/dielectric bases corresponding to qmesh:
	logPrintf("Setting up reduced polarizability bases at Ecut = %lg: ", Ecut); logFlush();
	basisChi.resize(qmesh.size());
	double avg_nbasis = 0.;
	const GridInfo& gInfoBasis = e.gInfoWfns ? *e.gInfoWfns : e.gInfo;
	logSuspend();
	for(size_t iq=0; iq<qmesh.size(); iq++)
	{	basisChi[iq].setup(gInfoBasis, e.iInfo, Ecut, qmesh[iq].k);
		avg_nbasis += qmesh[iq].weight * basisChi[iq].nbasis;
	}
	logResume();
	logPrintf("nbasis = %.2lf average, %.2lf ideal\n", avg_nbasis, pow(sqrt(2*Ecut),3)*(e.gInfo.detR/(6*M_PI*M_PI)));
	logFlush();


	//Initialize common wavefunction basis and ColumnBundle transforms for full k-mesh:
	logPrintf("Setting up k-mesh wavefunction transforms ... "); logFlush();
	double kMaxSq = 0;
	for(const vector3<>& k: supercell->kmesh)
	{	kMaxSq = std::max(kMaxSq, e.gInfo.GGT.metric_length_squared(k));
		for(const QuantumNumber& qnum: qmesh)
			kMaxSq = std::max(kMaxSq, e.gInfo.GGT.metric_length_squared(k + qnum.k));
	}
	double kWeight = double(e.eInfo.spinWeight) / supercell->kmesh.size();
	double GmaxEff = sqrt(2.*e.cntrl.Ecut) + sqrt(kMaxSq);
	double EcutEff = 0.5*GmaxEff*GmaxEff * (1.+symmThreshold); //add some margin for round-off error safety
	logSuspend();
	basis.setup(e.gInfo, e.iInfo, EcutEff, vector3<>());
	logResume();
	ColumnBundleTransform::BasisWrapper basisWrapper(basis);
	std::vector<matrix3<int>> sym = e.symm.getMatrices();
	for(size_t ik=ikStart; ik<ikStop; ik++)
	{	const vector3<>& k = supercell->kmesh[ik];
		for(const QuantumNumber& qnum: qmesh)
		{	vector3<> k2 = k + qnum.k; double roundErr;
			vector3<int> k2sup = round((k2 - supercell->kmesh[0]) * supercell->super, &roundErr);
			myassert(roundErr < symmThreshold);
			auto iter = transform.find(k2sup);
			if(iter == transform.end())
			{	size_t ik2 = plook->find(k2); myassert(ik2 != string::npos);
				const Supercell::KmeshTransform& kTransform = supercell->kmeshTransform[ik2];
				const Basis& basisC = e.basis[kTransform.iReduced];
				const vector3<>& kC = e.eInfo.qnums[kTransform.iReduced].k;
				transform[k2sup] = std::make_shared<ColumnBundleTransform>(kC, basisC, k2, basisWrapper,
					nSpinor, sym[kTransform.iSym], kTransform.invert);
				//Initialize corresponding quantum number:
				QuantumNumber qnum;
				qnum.k = k2;
				qnum.spin = 0;
				qnum.weight = kWeight;
				qnumMesh[k2sup] = qnum;
			}
		}
	}
	logPrintf("done.\n"); logFlush();

	//Main loop over momentum transfers:
	diagMatrix ImKscrHead(omegaGrid.size(), 0.);
	std::vector<diagMatrix> ImSigma(e.eInfo.nStates, diagMatrix(nBands,0.));
	diagMatrix cedaNum(nBands, 0.), cedaDen(nBands, 0.);
	for(size_t iq=0; iq<qmesh.size(); iq++)
	{	logPrintf("\nMomentum transfer %d of %d: q = ", int(iq+1), int(qmesh.size()));
		qmesh[iq].k.print(globalLog, " %+.5lf ");
		int nbasis = basisChi[iq].nbasis;
		
		//Construct Coulomb operator (regularizes G=0 using the tricks developed for EXX):
		matrix invKq = inv(coulombMatrix(iq));
		
		//Calculate chi_KS:
		std::vector<matrix> chiKS(omegaGrid.nRows()); CEDA ceda(nBands, nbasis);
		logPrintf("\tComputing chi_KS ...  "); logFlush(); 
		size_t nkMine = ikStop-ikStart;
		int ikInterval = std::max(1, int(round(nkMine/20.))); //interval for reporting progress
		for(size_t ik=ikStart; ik<ikStop; ik++)
		{	//Report progress:
			size_t ikDone = ik-ikStart+1;
			if(ikDone % ikInterval == 0)
			{	logPrintf("%d%% ", int(round(ikDone*100./nkMine)));
				logFlush();
			}
			//Get events:
			size_t jk; matrix nij;
			std::vector<Event> events = getEvents(true, ik, iq, jk, nij, &ceda);
			if(!events.size()) continue;
			//Collect contributions for each frequency:
			for(int iOmega=0; iOmega<omegaGrid.nRows(); iOmega++)
			{	double omega = omegaGrid[iOmega];
				complex omegaTilde(omega, 2*eta);
				complex one(1,0);
				std::vector<complex> Xks; Xks.reserve(events.size());
				for(const Event& event: events)
					Xks.push_back(-e.gInfo.detR * kWeight * event.fWeight
						* (one/(event.Eji - omegaTilde) + one/(event.Eji + omegaTilde)) );
				chiKS[iOmega] += (nij * Xks) * dagger(nij);
			}
		}
		for(int iOmega=0; iOmega<omegaGrid.nRows(); iOmega++)
			chiKS[iOmega].allReduce(MPIUtil::ReduceSum);
		logPrintf("done.\n"); logFlush();
		diagMatrix chiKS0diag = diag(chiKS[0]); //static neglecting local-fields (for CEDA)
		
		//Figure out head entry index:
		int iHead = -1;
		for(int n=0; n<nbasis; n++)
			if(!basisChi[iq].iGarr[n].length_squared())
			{	iHead = n;
				break;
			}
		myassert(iHead >= 0);
		
		//Calculate Im(screened Coulomb operator):
		logPrintf("\tComputing Im(Kscreened) ... "); logFlush();
		std::vector<matrix> ImKscr(omegaGrid.nRows(), zeroes(nbasis, nbasis));
		for(int iOmega=iOmegaStart; iOmega<iOmegaStop; iOmega++)
		{	ImKscr[iOmega] = imag(inv(invKq - chiKS[iOmega]));
			chiKS[iOmega] = 0; //free to save memory
			ImKscrHead[iOmega] += qmesh[iq].weight * ImKscr[iOmega](iHead,iHead).real(); //accumulate head of ImKscr
		}
		for(int iOmega=0; iOmega<omegaGrid.nRows(); iOmega++)
			ImKscr[iOmega].bcast(omegaDiv.whose(iOmega));
		chiKS.clear();
		logPrintf("done.\n"); logFlush();
		
		//Collect CEDA contributions:
		ceda.collect(*this, iq, chiKS0diag, cedaNum, cedaDen);
		
		//Calculate ImSigma contributions:
		logPrintf("\tComputing ImSigma ... "); logFlush(); 
		for(size_t ik=ikStart; ik<ikStop; ik++)
		{	//Report progress:
			size_t ikDone = ik-ikStart+1;
			if(ikDone % ikInterval == 0)
			{	logPrintf("%d%% ", int(round(ikDone*100./nkMine)));
				logFlush();
			}
			//Get events:
			size_t jk; matrix nij;
			std::vector<Event> events = getEvents(false, ik, iq, jk, nij);
			if(!events.size()) continue;
			//Integrate over frequency for event contributions to linewidth:
			diagMatrix eventContrib(events.size(), 0);
			for(int iOmega=0; iOmega<omegaGrid.nRows(); iOmega++)
			{	//Construct energy conserving delta-function:
				double omega = omegaGrid[iOmega];
				complex omegaTilde(omega, 2*eta);
				diagMatrix delta; delta.reserve(events.size());
				for(const Event& event: events)
					delta.push_back(e.gInfo.detR * event.fWeight //overlap and sign for electron / hole
						* (2*eta/M_PI) * ( 1./(event.Eji - omegaTilde).norm() - 1./(event.Eji + omegaTilde).norm()) ); //Normalized Lorentzians
				eventContrib += wOmega[iOmega] * delta * diag(dagger(nij) * ImKscr[iOmega] * nij);
			}
			//Accumulate contributions to linewidth:
			int iReduced = supercell->kmeshTransform[ik].iReduced; //directly collect to reduced k-point
			double symFactor = e.eInfo.spinWeight / (supercell->kmesh.size() * e.eInfo.qnums[iReduced].weight); //symmetrization factor = 1 / |orbit of iReduced|
			double qWeight = qmesh[iq].weight;
			for(size_t iEvent=0; iEvent<events.size(); iEvent++)
			{	const Event& event = events[iEvent];
				ImSigma[iReduced][event.i] += symFactor * qWeight * eventContrib[iEvent];
			}
		}
		logPrintf("done.\n"); logFlush();
	}
	logPrintf("\n");
	
	ImKscrHead.allReduce(MPIUtil::ReduceSum);
	for(diagMatrix& IS: ImSigma)
		IS.allReduce(MPIUtil::ReduceSum);
	for(int q=0; q<e.eInfo.nStates; q++)
		for(int b=0; b<nBands; b++)
		{	double Eqb = E[q][b];
			if(Eqb<Emin || Eqb>Emax)
				ImSigma[q][b] = NAN; //clearly mark as invalid
		}
	
	string fname = e.dump.getFilename("ImSigma_ee");
	logPrintf("Dumping %s ... ", fname.c_str()); logFlush();
	e.eInfo.write(ImSigma, fname.c_str());
	logPrintf("done.\n");

	fname = e.dump.getFilename("ImKscrHead");
	logPrintf("Dumping %s ... ", fname.c_str()); logFlush();
	if(mpiUtil->isHead())
	{	FILE* fp = fopen(fname.c_str(), "w");
		for(int iOmega=0; iOmega<omegaGrid.nRows(); iOmega++)
			fprintf(fp, "%lf %le\n", omegaGrid[iOmega], ImKscrHead[iOmega]);
		fclose(fp);
	}
	logPrintf("done.\n");

	fname = e.dump.getFilename("CEDA");
	logPrintf("Dumping %s ... ", fname.c_str()); logFlush();
	if(mpiUtil->isHead())
	{	FILE* fp = fopen(fname.c_str(), "w");
		if(!fp) die("Could not open '%s' for writing.\n", fname.c_str());
		(cedaNum * inv(cedaDen)).print(fp, "%19.12le\n");
		fclose(fp);
	}
	logPrintf("done.\n");

	logPrintf("\n"); logFlush();
}