Exemple #1
0
//Initialize
static void init(void)
{
  Ez = (double complex*)malloc(sizeof(double complex)*N_CELL);
  Dz = (double complex*)malloc(sizeof(double complex)*N_CELL);
  Jz = (double complex*)malloc(sizeof(double complex)*N_CELL);
  
  Hx = (double complex*)malloc(sizeof(double complex)*N_CELL);
  Mx = (double complex*)malloc(sizeof(double complex)*N_CELL);
  Bx = (double complex*)malloc(sizeof(double complex)*N_CELL);
  
  Hy = (double complex*)malloc(sizeof(double complex)*N_CELL);
  My = (double complex*)malloc(sizeof(double complex)*N_CELL);
  By = (double complex*)malloc(sizeof(double complex)*N_CELL);

  C_JZ = (double *)malloc(sizeof(double)*N_CELL);
  C_MX = (double *)malloc(sizeof(double)*N_CELL);
  C_MY = (double *)malloc(sizeof(double)*N_CELL);

  C_DZ = (double *)malloc(sizeof(double)*N_CELL);
  C_BX = (double *)malloc(sizeof(double)*N_CELL);
  C_BY = (double *)malloc(sizeof(double)*N_CELL);

  C_JZHXHY = (double *)malloc(sizeof(double)*N_CELL);
  C_MXEZ = (double *)malloc(sizeof(double)*N_CELL);
  C_MYEZ = (double *)malloc(sizeof(double)*N_CELL);

  C_DZJZ0 = (double *)malloc(sizeof(double)*N_CELL);
  C_DZJZ1 = (double *)malloc(sizeof(double)*N_CELL);

  C_BXMX1 = (double *)malloc(sizeof(double)*N_CELL);
  C_BXMX0 = (double *)malloc(sizeof(double)*N_CELL);

  C_BYMY1 = (double *)malloc(sizeof(double)*N_CELL);
  C_BYMY0 = (double *)malloc(sizeof(double)*N_CELL);

  EPS_HY = (double *)malloc(sizeof(double)*N_CELL);
  EPS_HX = (double *)malloc(sizeof(double)*N_CELL);
  EPS_EZ = (double *)malloc(sizeof(double)*N_CELL);

  memset(Hx, 0, sizeof(double complex)*N_CELL);
  memset(Hy, 0, sizeof(double complex)*N_CELL);
  memset(Ez, 0, sizeof(double complex)*N_CELL);

  memset(Mx, 0, sizeof(double complex)*N_CELL);
  memset(My, 0, sizeof(double complex)*N_CELL);
  memset(Jz, 0, sizeof(double complex)*N_CELL);

  memset(Bx, 0, sizeof(double complex)*N_CELL);
  memset(By, 0, sizeof(double complex)*N_CELL);
  memset(Dz, 0, sizeof(double complex)*N_CELL);

  //Ez,, Hx, Hyそれぞれでσx,σyが違う(場所が違うから)
  double sig_ez_x, sig_ez_y;
  double sig_hx_x, sig_hx_y;
  double sig_hy_x, sig_hy_y;
  
  const double R = 1.0e-8;
  const double M = 2.0;
  //  const double sig_max = -(M+1.0)*EPSILON_0_S*LIGHT_SPEED_S/2.0/N_PML*log(R);
  const double sig_max = -(M+1.0)*EPSILON_0_S*LIGHT_SPEED_S/2.0/N_PML/cos(M_PI/3)*log(R);
  for(int i=0; i<N_PX; i++){
    for(int j=0; j<N_PY; j++){
      EPS_EZ[ind(i,j)] = models_eps(i,j, D_XY);     //todo D_X, D_Yにしなくていいのか?
      EPS_HX[ind(i,j)] = models_eps(i,j+0.5, D_XY);
      EPS_HY[ind(i,j)] = models_eps(i+0.5,j, D_XY);
      
      sig_ez_x = sig_max*field_sigmaX(i,j);
      sig_ez_y = sig_max*field_sigmaY(i,j);

      sig_hx_x = sig_max*field_sigmaX(i,j+0.5);
      sig_hx_y = sig_max*field_sigmaY(i,j+0.5);
      
      sig_hy_x = sig_max*field_sigmaX(i+0.5,j);
      sig_hy_y = sig_max*field_sigmaY(i+0.5,j);

      double sig_z = 0; // σz is zero in 2D ? todo
      
      //Δt = 1  Κ_i = 1
      double eps = EPSILON_0_S;
      
      C_JZ[ind(i,j)]     = ( 2*eps - sig_ez_x) / (2*eps + sig_ez_x);
      C_JZHXHY[ind(i,j)] = ( 2*eps ) / (2*eps + sig_ez_x);
      C_DZ[ind(i,j)]     = ( 2*eps - sig_ez_y)  / (2*eps + sig_ez_y);      
      C_DZJZ1[ind(i,j)]  = ( 2*eps + sig_z)/(2*eps + sig_ez_y);
      C_DZJZ0[ind(i,j)]  = ( 2*eps - sig_z)/(2*eps + sig_ez_y);

      C_MX[ind(i,j)]    = (2*eps - sig_hx_y) / (2*eps + sig_hx_y);
      C_MXEZ[ind(i,j)]  = (2*eps) / (2*eps + sig_hx_y);
      C_BX[ind(i,j)]    = (2*eps - sig_z) / (2*eps + sig_z);
      C_BXMX1[ind(i,j)] = (2*eps + sig_hx_x) / (2*eps + sig_z);
      C_BXMX0[ind(i,j)] = (2*eps - sig_hx_x) / (2*eps + sig_z);
      
      C_MY[ind(i,j)]    = (2*eps - sig_z) / (2*eps + sig_z);
      C_MYEZ[ind(i,j)]  = (2*eps) / (2*eps + sig_z);      
      C_BY[ind(i,j)]    = (2*eps - sig_hy_x) / (2*eps + sig_hy_x);
      C_BYMY1[ind(i,j)] = (2*eps + sig_hy_y) / (2*eps + sig_hy_x);
      C_BYMY0[ind(i,j)] = (2*eps - sig_hy_y) / (2*eps + sig_hy_x);
      
    }
  }
}
Exemple #2
0
// -----------------------------------------------------------------------------
// CBerTlv::TlvByTagValue
// Find TLV by tag value. aTlv is set to point to found TLV. If there are more
// than one TLV with the same tag then itemNbr can be used to select which one
// is returned. If no tags are found return KErrNotFound else KErrNone.
// -----------------------------------------------------------------------------
//
EXPORT_C TInt CBerTlv::TlvByTagValue
(
    CTlv* aTlv,                 // TLV
    TUint8 aTlvTagValue,        // TLV identifier
    TInt itemNbr                // Item number
)
{
    OstTraceDef0(OST_TRACE_CATEGORY_DEBUG, TRACE_BORDER, CBERTLV_TLVBYTAGVALUE_1, "UTILITY: CBerTlv::TlvByTagValue");
    TInt currentTlv( 0 );
    TInt tlvLength( 0 );
    TInt index( 0 );

    // TLV start index
    TInt ind( KCommonTlvHeaderLength );
    TUint8 berTlvLength( 0 );
    if ( KTwoByteLengthCoding == iData[KTlvLengthStartPosition] )
    {
        berTlvLength = iData[KTlvLengthStartPosition + 1];
        ind = ind + 1;
    }
    else
    {
        berTlvLength = iData[KTlvLengthStartPosition];
    }

    for ( TInt i = 0; i < berTlvLength; i += tlvLength )
    {
        // First determine if the length of the TLV is coded with 1 or 2 bytes.
        if ( KTwoByteLengthCoding == iData[ind + 1] )
        {
            // Length is coded with 2 bytes -> 1 extra byte required to be
            // added to total length. Also TLV header bytes (2) must be added
            // to total length
            tlvLength = iData[ind + 2] + KTlvHeaderLength + 1;
        }
        else
        {
            // TLV header bytes (2) must be added to total length
            tlvLength = iData[ind + 1] + KTlvHeaderLength;
        }

        currentTlv = iData[ind]&KTagValueMask;

        // Check if TLV in current index is the one that we are searching for
        if ( aTlvTagValue == currentTlv )
        {
            if( index == itemNbr)
            {
                TPtrC8 data = ( iData.Mid( ind , tlvLength ) );
                aTlv->SetData( data );
                return KErrNone;
            }
            else
            {
                index++;
            }
        }

        ind += tlvLength;
    }

    return KErrNotFound;
}
Exemple #3
0
    /// Perform actual tests
    template<class Array> bool runTestForArray(Array& a) {
      // Test/problem information.
      const char* test    = "NONE";
      const char* problem = "NONE";
      // Constant reference to the array
      const Array& const_a = a;

      START_TEST("Iteration");
      {
        typedef typename Array::reference reference;
        typedef typename Array::pointer pointer;
        typedef typename Array::iterator iterator;
        const iterator begin = a.begin(), end = a.end();
        CHECK_TEST(end-begin==a.size(),"Distance != size");
        int index = 0;
        iterator iter = begin;
        for(; iter != end; ++iter, ++index) {
          reference ref = *iter;
          const pointer ptr = &ref;
          CHECK_TEST(ptr==&a[index],"Iterator points to the wrong element (going forward)");
        }
        CHECK_TEST(index==a.size(),"Iteration covered the wrong number of elements (going forward)");
        for(; iter != begin; --iter, --index) {
          reference ref = *(iter-1);
          const pointer ptr = &ref;
          CHECK_TEST(ptr==&a[index-1],"Iterator points to the wrong element (going backwards)");
        }
        CHECK_TEST(index==0,"Iteration covered the wrong number of elements (going backward)");
      }
      START_TEST("Read-only iteration");
      {
        typedef typename Array::const_reference reference;
        typedef typename Array::const_pointer pointer;
        typedef typename Array::const_iterator iterator;
        const iterator begin = const_a.begin(), end = const_a.end();
        CHECK_TEST(end-begin==const_a.size(),"Distance != size");
        int index = 0;
        iterator iter = begin;
        for(; iter != end; ++iter, ++index) {
          reference ref = *iter;
          const pointer ptr = &ref;
          CHECK_TEST(ptr==&const_a[index],"Iterator points to the wrong element (going forward)");
        }
        CHECK_TEST(index==const_a.size(),"Iteration covered the wrong number of elements (going forward)");
        for(; iter != begin; --iter, --index) {
          reference ref = *(iter-1);
          const pointer ptr = &ref;
          CHECK_TEST(ptr==&const_a[index-1],"Iterator points to the wrong element (going backwards)");
        }
        CHECK_TEST(index==0,"Iteration covered the wrong number of elements (going backward)");
      }

      START_TEST("Reverse iteration");
      {
        typedef typename Array::reference reference;
        typedef typename Array::pointer pointer;
        typedef typename Array::reverse_iterator iterator;
        const iterator begin = a.rbegin(), end = a.rend();
        CHECK_TEST(end-begin==a.size(),"Distance != size");
        int index = a.size();
        iterator iter = begin;
        for(; iter != end; ++iter, --index) {
          reference ref = *iter;
          const pointer ptr = &ref;
          CHECK_TEST(ptr==&a[index-1],"Iterator points to the wrong element (going forward)");
        }
        CHECK_TEST(index==0,"Iteration covered the wrong number of elements (going forward)");
        for(; iter != begin; --iter, ++index) {
          reference ref = *(iter-1);
          const pointer ptr = &ref;
          CHECK_TEST(ptr==&a[index],"Iterator points to the wrong element (going backwards)");
        }
        CHECK_TEST(index==a.size(),"Iteration covered the wrong number of elements (going backward)");
      }

      START_TEST("Reverse read-only iteration");
      {
        typedef typename Array::const_reference reference;
        typedef typename Array::const_pointer pointer;
        typedef typename Array::const_reverse_iterator iterator;
        const iterator begin = const_a.rbegin(), end = const_a.rend();
        CHECK_TEST(end-begin==const_a.size(),"Distance != size");
        int index = a.size();
        iterator iter = begin;
        for(; iter != end; ++iter, --index) {
          reference ref = *iter;
          const pointer ptr = &ref;
          CHECK_TEST(ptr==&const_a[index-1],"Iterator points to the wrong element (going forward)");
        }
        CHECK_TEST(index==0,"Iteration covered the wrong number of elements (going forward)");
        for(; iter != begin; --iter, ++index) {
          reference ref = *(iter-1);
          const pointer ptr = &ref;
          CHECK_TEST(ptr==&const_a[index],"Iterator points to the wrong element (going backwards)");
        }
        CHECK_TEST(index==a.size(),"Iteration covered the wrong number of elements (going backward)");
      }

      return true;
    failed:
      if (opt.log)
        olog << "FAILURE" << std::endl
        << ind(1) << "Test:       " << test << std::endl
        << ind(1) << "Problem:    " << problem << std::endl;
      return false;
    }
Exemple #4
0
void KoulesSimulator::markAsDead(unsigned int i)
{
    unsigned int ii = ind(i);
    qcur_[ii] = -2. * kouleRadius;
    qcur_[ii + 1] = qcur_[ii + 2] = qcur_[ii + 3] = 0.;
}
Exemple #5
0
int main(int argc, char **argv)
{
    int r,p;
    int n, energy, niters, px, py;

    int rx, ry;
    int north, south, west, east;
    int bx, by, offx, offy;

    /* three heat sources */
    const int nsources = 3;
    int sources[nsources][2];
    int locnsources;             /* number of sources in my area */
    int locsources[nsources][2]; /* sources local to my rank */

    double t1, t2;

    int iter, i, j;

    double heat, rheat;

    int final_flag;

    /* initialize MPI envrionment */
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &r);
    MPI_Comm_size(MPI_COMM_WORLD, &p);

    /* create shared memory communicator */
    MPI_Comm shmcomm;
    MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL, &shmcomm);

    int sr, sp; // rank and size in shmem comm
    MPI_Comm_size(shmcomm, &sp);
    MPI_Comm_rank(shmcomm, &sr);

    // this code works only on comm world!
    if(sp != p) MPI_Abort(MPI_COMM_WORLD, 1);

    /* argument checking and setting */
    setup(r, p, argc, argv,
          &n, &energy, &niters, &px, &py, &final_flag);

    if (final_flag == 1) {
        MPI_Finalize();
        exit(0);
    }

    /* determine my coordinates (x,y) -- r=x*a+y in the 2d processor array */
    rx = r % px;
    ry = r / px;

    /* determine my four neighbors */
    north = (ry - 1) * px + rx; if (ry-1 < 0)   north = MPI_PROC_NULL;
    south = (ry + 1) * px + rx; if (ry+1 >= py) south = MPI_PROC_NULL;
    west = ry * px + rx - 1;    if (rx-1 < 0)   west = MPI_PROC_NULL;
    east = ry * px + rx + 1;    if (rx+1 >= px) east = MPI_PROC_NULL;

    /* decompose the domain */
    bx = n / px;    /* block size in x */
    by = n / py;    /* block size in y */
    offx = rx * bx; /* offset in x */
    offy = ry * by; /* offset in y */

    /* printf("%i (%i,%i) - w: %i, e: %i, n: %i, s: %i\n", r, ry,rx,west,east,north,south); */

    int size = (bx+2)*(by+2); /* process-local grid (including halos (thus +2)) */
    double *mem;
    MPI_Win win;
    MPI_Win_allocate_shared(2*size*sizeof(double), 1, MPI_INFO_NULL, shmcomm, &mem, &win);

    double *tmp;
    double *anew=mem; /* each rank's offset */
    double *aold=mem+size; /* second half is aold! */

    double *northptr, *southptr, *eastptr, *westptr;
    double *northptr2, *southptr2, *eastptr2, *westptr2;
    MPI_Aint sz;
    int dsp_unit;
    /* locate the shared memory region for each neighbor */
    MPI_Win_shared_query(win, north, &sz, &dsp_unit, &northptr);
    MPI_Win_shared_query(win, south, &sz, &dsp_unit, &southptr);
    MPI_Win_shared_query(win, east, &sz, &dsp_unit, &eastptr);
    MPI_Win_shared_query(win, west, &sz, &dsp_unit, &westptr);
    northptr2 = northptr+size;
    southptr2 = southptr+size;
    eastptr2 = eastptr+size;
    westptr2 = westptr+size;

    /* initialize three heat sources */
    init_sources(bx, by, offx, offy, n,
                 nsources, sources, &locnsources, locsources);

    t1 = MPI_Wtime(); /* take time */

    MPI_Win_lock_all(0, win);    
    for (iter = 0; iter < niters; ++iter) {
        /* refresh heat sources */
        for (i = 0; i < locnsources; ++i) {
            aold[ind(locsources[i][0],locsources[i][1])] += energy; /* heat source */
        }

	MPI_Win_sync(win);
	MPI_Barrier(shmcomm);

	/* exchange data with neighbors */
	if(north != MPI_PROC_NULL) {
	  for(i=0; i<bx; ++i) aold[ind(i+1,0)] = northptr2[ind(i+1,by)]; /* pack loop - last valid region */
	}
	if(south != MPI_PROC_NULL) {
	  for(i=0; i<bx; ++i) aold[ind(i+1,by+1)] = southptr2[ind(i+1,1)]; /* pack loop */
	}
	if(east != MPI_PROC_NULL) {
	  for(i=0; i<by; ++i) aold[ind(bx+1,i+1)] = eastptr2[ind(1,i+1)]; /* pack loop */
	}
	if(west != MPI_PROC_NULL) {
	  for(i=0; i<by; ++i) aold[ind(0,i+1)] = westptr2[ind(bx,i+1)]; /* pack loop */
	}

        /* update grid points */
        update_grid(bx, by, aold, anew, &heat);

        /* swap working arrays */
        tmp = anew; anew = aold; aold = tmp;

        /* optional - print image */
        if (iter == niters-1) printarr_par(iter, anew, n, px, py, rx, ry, bx, by, offx, offy, shmcomm);
    }

    MPI_Win_unlock_all(win);
    t2 = MPI_Wtime();

    /* get final heat in the system */
    MPI_Allreduce(&heat, &rheat, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
    if (!r) printf("[%i] last heat: %f time: %f\n", r, rheat, t2-t1);

    /* free working arrays and communication buffers */
    MPI_Win_free(&win);
    MPI_Comm_free(&shmcomm);

    MPI_Finalize();
}
eap_status_e asn1_der_type_c::debug_object_identifier(eap_variable_data_c * const debug_buffer)
{
	if (debug_buffer == 0)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_illegal_parameter);
	}

	eap_status_e status(eap_status_process_general_error);

	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	status = debug_buffer->set_data_length(debug_buffer->get_buffer_length());
	if (status != eap_status_ok)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, status);
	}

	const u32_t recursion(m_recursion + 1u);
	const u32_t max_prefix_length(recursion * SIZE_OF_ONE_OCTET_STRING + 1ul);

	if (debug_buffer->get_buffer_length() < (max_prefix_length + 2ul))
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_allocation_error);
	}

	const u32_t max_data_output_length((debug_buffer->get_buffer_length() - (max_prefix_length + 2ul))/2ul);
	const u32_t max_plain_output_length(max_data_output_length);

	u32_t prefix_length(0ul);

	u8_t * const prefix = debug_buffer->get_data();
	if (prefix == 0)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_illegal_parameter);
	}

	status = debug_create_prefix(recursion, prefix, max_prefix_length, &prefix_length);
	if (status != eap_status_ok)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, status);
	}

	u8_t * const data_output = debug_buffer->get_data_offset(max_prefix_length, max_data_output_length);
	if (data_output == 0)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_allocation_error);
	}
	data_output[max_data_output_length-1ul] = 0;

	u8_t * const plain_output = debug_buffer->get_data_offset(max_prefix_length + max_data_output_length, max_plain_output_length);
	if (plain_output == 0)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_allocation_error);
	}
	plain_output[max_plain_output_length - 1ul] = 0;

	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	const u32_t length = get_content_length();
	
	if (length == 0)
	{
		EAP_TRACE_DEBUG(
			m_am_tools,
			TRACE_FLAGS_DEFAULT,
			(EAPL("# ERROR: invalid %s, length=%d\n"),
				get_tag_string(),
				length));

		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_buffer_too_short);
	}

	const u8_t * const oid_data = get_content();

	if (oid_data == 0)
	{
		EAP_TRACE_DEBUG(
			m_am_tools,
			TRACE_FLAGS_DEFAULT,
			(EAPL("# ERROR: invalid %s, length=%d\n"),
				get_tag_string(),
				length));

		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_buffer_too_short);
	}

	u32_t offset(0ul);
	u8_t oid_octet = oid_data[offset];
	u32_t oid1 = oid_octet / 40;
	u32_t oid2 = (oid_octet - oid1*40);

	EAP_TRACE_DEBUG(
		m_am_tools,
		TRACE_FLAGS_DEFAULT,
		(EAPL("%s%02x # = %d = 40 * %d + %d => %d.%d\n"),
		prefix,
		oid_octet,
		oid_octet,
		oid1,
		oid2,
		oid1,
		oid2));

	++offset;

	while(offset < length)
	{
		u32_t oid_length(0ul);
		u32_t data_output_offset(0ul);
		u32_t plain_output_offset(0ul);
		u32_t ind(0ul);

		for (ind = offset; ind < length; ++ind)
		{
			u8_t oid_octet = oid_data[ind];
			++oid_length;
			if ((oid_octet & OID_HIGH_BIT) == 0)
			{
				break;
			}
		} // for()

		u32_t power = oid_length - 1ul;
		u32_t oid_value(0ul);

		for (ind = offset; ind < (offset+oid_length); ++ind)
		{
			u8_t oid_octet = oid_data[ind];

			data_output_offset += m_am_tools->snprintf(
				&data_output[data_output_offset],
				max_data_output_length - data_output_offset,
				"%02x \0",
				oid_octet);

			u8_t oid = static_cast<u8_t>(oid_octet & (~OID_HIGH_BIT));

			if (ind > offset)
			{
				plain_output_offset += m_am_tools->snprintf(
					&plain_output[plain_output_offset],
					max_data_output_length - plain_output_offset,
					" + \0");
			}

			if (power > 1ul)
			{
				plain_output_offset += m_am_tools->snprintf(
					&plain_output[plain_output_offset],
					max_data_output_length - plain_output_offset,
					"0x%02x * 128 ^ %d\0",
					oid,
					power);
			}
			else if (power > 0ul)
			{
				plain_output_offset += m_am_tools->snprintf(
					&plain_output[plain_output_offset],
					max_data_output_length - plain_output_offset,
					"0x%02x * 128\0",
					oid);
			}
			else
			{
				plain_output_offset += m_am_tools->snprintf(
					&plain_output[plain_output_offset],
					max_data_output_length - plain_output_offset,
					"0x%02x\0",
					oid);
			}

			oid_value = (oid_value << 7) + oid;

			--power;
		} // for()

		EAP_TRACE_DEBUG(
			m_am_tools,
			TRACE_FLAGS_DEFAULT,
			(EAPL("%s%s # %s = %d\n"),
			prefix,
			data_output,
			plain_output,
			oid_value));

		offset += oid_length;
	}

	EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
	return EAP_STATUS_RETURN(m_am_tools, status);
}
int main(int argc, char **argv)
{
    int rank, size;
    int n, energy, niters, px, py;

    int north, south, west, east;
    int bx, by, offx, offy;

    /* three heat sources */
    const int nsources = 3;
    int sources[nsources][2];
    int locnsources;             /* number of sources in my area */
    int locsources[nsources][2]; /* sources local to my rank */

    double t1, t2;

    int iter, i;

    double *aold, *anew, *tmp;

    double heat, rheat;

    int final_flag;

    /* initialize MPI envrionment */
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    /* argument checking and setting */
    setup(rank, size, argc, argv,
          &n, &energy, &niters, &px, &py, &final_flag);

    if (final_flag == 1) {
        MPI_Finalize();
        exit(0);
    }

    /* Create a communicator with a topology */
    MPI_Comm cart_comm;
    int dims[2] = {0,0}, periods[2] = {0,0}, coords[2];
    MPI_Dims_create(size, 2, dims);
    MPI_Cart_create(MPI_COMM_WORLD, 2, dims, periods, 0, &cart_comm);
    MPI_Cart_coords(cart_comm, rank, 2, coords);

    /* determine my four neighbors */
    MPI_Cart_shift(cart_comm, 0, 1, &west, &east);
    MPI_Cart_shift(cart_comm, 1, 1, &north, &south);

    /* decompose the domain */
    bx = n / px;    /* block size in x */
    by = n / py;    /* block size in y */
    offx = coords[0] * bx; /* offset in x */
    offy = coords[1] * by; /* offset in y */

    /* printf("%i (%i,%i) - w: %i, e: %i, n: %i, s: %i\n", rank, ry,rx,west,east,north,south); */

    /* allocate working arrays & communication buffers */
    MPI_Alloc_mem((bx+2)*(by+2)*sizeof(double), MPI_INFO_NULL, &aold); /* 1-wide halo zones! */
    MPI_Alloc_mem((bx+2)*(by+2)*sizeof(double), MPI_INFO_NULL, &anew); /* 1-wide halo zones! */

    /* initialize three heat sources */
    init_sources(bx, by, offx, offy, n,
                 nsources, sources, &locnsources, locsources);

    /* create north-south datatype */
    MPI_Datatype north_south_type;
    MPI_Type_contiguous(bx, MPI_DOUBLE, &north_south_type);
    MPI_Type_commit(&north_south_type);

    /* create east-west type */
    MPI_Datatype east_west_type;
    MPI_Type_vector(by,1,by+2,MPI_DOUBLE, &east_west_type);
    MPI_Type_commit(&east_west_type);

    t1 = MPI_Wtime(); /* take time */

    for (iter = 0; iter < niters; ++iter) {

        /* refresh heat sources */
        for (i = 0; i < locnsources; ++i) {
            aold[ind(locsources[i][0],locsources[i][1])] += energy; /* heat source */
        }

        /* exchange data with neighbors */
        int counts[4] = {1, 1, 1, 1};
        MPI_Aint sdispls[4] = {ind(1,1), ind(1,by), ind(1,1), ind(bx,1)}; /* N, S, W, E */
        MPI_Aint rdispls[4] = {ind(1,0), ind(1,by+1), ind(0,1), ind(bx+1,1)};
        MPI_Datatype types[4] = {north_south_type, north_south_type, east_west_type, east_west_type};
        MPI_Neighbor_alltoallw(aold, counts, sdispls, types, anew, counts, rdispls, types, cart_comm);

        /* update grid points */
        update_grid(bx, by, aold, anew, &heat);

        /* swap working arrays */
        tmp = anew; anew = aold; aold = tmp;

        /* optional - print image */
        if (iter == niters-1)
            printarr_par(iter, anew, n, px, py, coords[0], coords[1],
                         bx, by, offx, offy, MPI_COMM_WORLD);
    }

    t2 = MPI_Wtime();

    /* free working arrays and communication buffers */
    MPI_Free_mem(aold);
    MPI_Free_mem(anew);

    MPI_Type_free(&east_west_type);
    MPI_Type_free(&north_south_type);

    /* get final heat in the system */
    MPI_Allreduce(&heat, &rheat, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
    if (!rank) printf("[%i] last heat: %f time: %f\n", rank, rheat, t2-t1);

    MPI_Finalize();
}
TEST(TrigradedIndex, Target)
{
  TrigradedIndex ind(2, 0, 0);
  TrigradedIndex ind_exp(0, 1, 1);
  EXPECT_EQ(ind_exp, target(ind, 2));
}
Exemple #9
0
	/*
	 * Person:  name,  id, 0, 0;
	 * File  :  name,  size, rank, (0) ts
	 * Dir   :  name,  (0) count, (0) path, (0) ts
	 */


	if (details.type == DIR_TYPE_PERSON) /* Person */
	{
		switch(coln)
		{
			case 0:
				return (RemoteMode)?(QString::fromUtf8(rsPeers->getPeerName(details.id).c_str())):tr("My files");
			case 1:
				return QString() ;
			case 2:
				return misc::userFriendlyDuration(details.min_age);
			default:
				return QString() ;
		}
	}
	else if (details.type == DIR_TYPE_FILE) /* File */
	{
		switch(coln)
		{
			case 0:
				return QString::fromUtf8(details.name.c_str());
			case 1:
				return  misc::friendlyUnit(details.count);
			case 2:
				return  misc::userFriendlyDuration(details.age);
			case 3:
				return getFlagsString(details.flags);
//			case 4:
//				{
//					QString ind("");
//					if (ageIndicator != IND_ALWAYS)
//						ind = getAgeIndicatorString(details);
//					return ind;
//				}
			case 4:
				return getGroupsString(details.parent_groups) ;

			default:
				return tr("FILE");
		}
	}
	else if (details.type == DIR_TYPE_DIR) /* Dir */
	{
		switch(coln)
		{
			case 0:
				return QString::fromUtf8(details.name.c_str());
				break;
			case 1:
				if (details.count > 1)
				{
					return QString::number(details.count) + " " + tr("Files");
				}
				return QString::number(details.count) + " " + tr("File");
			case 2:
				return misc::userFriendlyDuration(details.min_age);
			case 3:
				return getFlagsString(details.flags);
			case 4: 
				return getGroupsString(details.parent_groups) ;

			default:
				return tr("DIR");
		}
	}
	return QVariant();
} /* end of DisplayRole */

QString FlatStyle_RDM::computeDirectoryPath(const DirDetails& details) const
{
	QString dir ;
	const DirDetails *det = requestDirDetails(details.parent,RemoteMode);

	if(!det)
		return QString(); 

#ifdef SHOW_TOTAL_PATH
	do
	{
#endif
		dir = QString::fromUtf8(det->name.c_str())+"/"+dir ;

#ifdef SHOW_TOTAL_PATH
		if(!requestDirDetails(det.parent,det,flags))
			break ;
	}
	while(det->parent != NULL);
#endif
	
	return dir ;
}

QVariant FlatStyle_RDM::displayRole(const DirDetails& details,int coln) const
{
	if (details.type == DIR_TYPE_FILE) /* File */
		switch(coln)
		{
			case 0: return QString::fromUtf8(details.name.c_str());
			case 1: return misc::friendlyUnit(details.count);
			case 2: return misc::userFriendlyDuration(details.age);
			case 3: return QString::fromUtf8(rsPeers->getPeerName(details.id).c_str());
			case 4: return computeDirectoryPath(details);
			default:
				return QVariant() ;
		}

	return QVariant();
} /* end of DisplayRole */
QVariant TreeStyle_RDM::sortRole(const QModelIndex& /*index*/,const DirDetails& details,int coln) const
{
	/*
	 * Person:  name,  id, 0, 0;
	 * File  :  name,  size, rank, (0) ts
	 * Dir   :  name,  (0) count, (0) path, (0) ts
	 */

	if (details.type == DIR_TYPE_PERSON) /* Person */
	{
		switch(coln)
		{
			case 0:
				return (RemoteMode)?(QString::fromUtf8(rsPeers->getPeerName(details.id).c_str())):tr("My files");
			case 1:
				return QString();
			case 2:
				return details.min_age;
			default:
				return QString();
		}
	}
	else if (details.type == DIR_TYPE_FILE) /* File */
	{
		switch(coln)
		{
			case 0:
				return QString::fromUtf8(details.name.c_str());
			case 1:
				return (qulonglong) details.count;
			case 2:
				return  details.age;
			case 3:
				return getFlagsString(details.flags);
			case 4:
				{
					QString ind("");
					if (ageIndicator != IND_ALWAYS)
						ind = getAgeIndicatorString(details);
					return ind;
				}
			default:
				return tr("FILE");
		}
	}
	else if (details.type == DIR_TYPE_DIR) /* Dir */
	{
		switch(coln)
		{
			case 0:
				return QString::fromUtf8(details.name.c_str());
			case 1:
				return (qulonglong) details.count;
			case 2:
				return details.min_age;
			case 3:
				return getFlagsString(details.flags);
			default:
				return tr("DIR");
		}
	}
	return QVariant();
}
 void process()
 {
  ind();
 }
TEST(TrigradedIndex, Source)
{
  TrigradedIndex ind(0, 1, 1);
  TrigradedIndex ind_exp(2, 0, 0);
  EXPECT_EQ(ind_exp, source(ind, 2));
}
Exemple #12
0
static inline double complex BY(const int i, const int j)
{
  return By[ind(i,j)];
}
Exemple #13
0
static inline double complex DZ(const int i, const int j)
{
  return Dz[ind(i,j)];
}
Exemple #14
0
static inline double complex HX(const int i, const int j)
{
  return Hx[ind(i,j)];
}
eap_status_e asn1_der_type_c::debug_header(eap_variable_data_c * const debug_buffer)
{
	if (debug_buffer == 0)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_illegal_parameter);
	}

	const u32_t max_data_length(m_recursion * SIZE_OF_ONE_OCTET_STRING + m_offset_of_contents_field * SIZE_OF_ONE_OCTET_STRING);

	if (max_data_length > debug_buffer->get_buffer_length())
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_allocation_error);
	}

	eap_status_e status = debug_buffer->set_data_length(max_data_length);
	if (status != eap_status_ok)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, status);
	}

	u32_t ind(0ul);
	u32_t offset(0ul);

	u8_t * const prefix = reinterpret_cast<u8_t *>(debug_buffer->get_data(max_data_length));

	if (prefix == 0)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_allocation_error);
	}

	status = debug_create_prefix(m_recursion, prefix, max_data_length, &offset);
	if (status != eap_status_ok)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, status);
	}

	for (ind = 0ul; ind < m_offset_of_length_field && ind < m_input_data_length; ++ind)
	{
		offset += m_am_tools->snprintf(
			debug_buffer->get_data_offset(offset, debug_buffer->get_data_length() - offset),
			debug_buffer->get_data_length() - offset,
			"%02x \0",
			m_input_data[ind]);
	}

	for (ind = m_offset_of_length_field; ind < m_offset_of_contents_field && ind < m_input_data_length; ++ind)
	{
		offset += m_am_tools->snprintf(
			debug_buffer->get_data_offset(offset, debug_buffer->get_data_length() - offset),
			debug_buffer->get_data_length() - offset,
			"%02x \0",
			m_input_data[ind]);
	}

	status = debug_buffer->add_end_null();
	if (status != eap_status_ok)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, status);
	}

	eap_const_string tag_string = 0;
	eap_char buffer[MAX_STACK_BUFFER];

	if (get_class() == asn1_class_application)
	{
		m_am_tools->snprintf(
			reinterpret_cast<u8_t *>(buffer),
			MAX_STACK_BUFFER,
			"Application[%d]\0",
			get_tag());

		tag_string = buffer;
	}
	else if (get_class() == asn1_class_context_specific)
	{
		m_am_tools->snprintf(
			reinterpret_cast<u8_t *>(buffer),
			MAX_STACK_BUFFER,
			"[%d]\0",
			get_tag());

		tag_string = buffer;
	}
	else
	{
		tag_string = get_tag_string();
	}

	EAP_TRACE_DEBUG(
		m_am_tools,
		TRACE_FLAGS_DEFAULT,
		(EAPL("%s # %s, %s, %s, length=0x%x=%d, this=0x%08x, index=%d\n"),
			debug_buffer->get_data(max_data_length),
			get_class_string(),
			get_pc_string(),
			tag_string,
			get_content_length(),
			get_content_length(),
			this,
			m_index));

	EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
	return EAP_STATUS_RETURN(m_am_tools, status);
}
void RecTestCase::TestIndividual()
{
    idt id;

    recIndividual record1;
    record1.f_id = 0;

    record1.FSetSex( SEX_Male );
    record1.f_surname     = "Matthews";
    record1.f_name        = "Nick Matthews";
    record1.f_epitaph     = "(1948-)";
    record1.f_note        = "A Note";
    record1.f_fam_id      = 4;
    // f_id = 0 so create new record and set f_id to new value.
    record1.Save();
    id = record1.f_id;
    CPPUNIT_ASSERT( id > 0 );

    recIndividual record2;
    record2.f_id = record1.f_id;
    record2.Read();
    CPPUNIT_ASSERT( record1 == record2 );

    record1.FSetSex( SEX_Male );
    record1.f_surname     = "Bloggs";
    record1.f_name        = "Fred Bloggs";
    record1.f_epitaph     = "(1948-)";
    record1.f_fam_id      = 18;
//    record1.f_per_id      = 17;
    // f_id = 1 which exists, so amend record leaving f_id to old value.
    record1.Save();
    CPPUNIT_ASSERT( record1.f_id == id );
    record2.Read();
    CPPUNIT_ASSERT( record1 == record2 );

    record1.f_id = 999;
    record1.f_surname = "Not wanted";
    // f_id = 999 which doesn't exists, so create new record with no change to f_id.
    record1.Save();
    CPPUNIT_ASSERT( record1.f_id == 999 );
    record2.f_id = record1.f_id;
    record2.Read();
    CPPUNIT_ASSERT( record1 == record2 );

    record1.f_id = 0;
    record1.f_surname = "Nor this";
    record1.Save();
    CPPUNIT_ASSERT( record1.f_id != 0 );
    CPPUNIT_ASSERT( record1.Exists() == true );
    record1.Delete();
    CPPUNIT_ASSERT( record1.Exists() == false );

    CPPUNIT_ASSERT( recIndividual::Exists( 999 ) == true );
    recIndividual::Delete( 999 );
    CPPUNIT_ASSERT( recIndividual::Exists( 999 ) == false );

    // Create some records for later testing
    recIndividual ind(0);
    ind.FSetID( 6 );
    ind.Save();
    ind.FSetID( 12 );
    ind.Save();
}
eap_status_e asn1_der_type_c::debug_data(eap_variable_data_c * const debug_buffer)
{
	if (debug_buffer == 0)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_illegal_parameter);
	}

	const u32_t max_prefix_length((m_recursion + 1ul) * SIZE_OF_ONE_OCTET_STRING + COUNT_OF_OCTETS * SIZE_OF_ONE_OCTET_STRING + 1ul);
	const u32_t ascii_length(COUNT_OF_OCTETS + 5ul);

	if ((max_prefix_length + ascii_length) > debug_buffer->get_buffer_length())
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_allocation_error);
	}

	eap_status_e status = debug_buffer->set_data_length(max_prefix_length + ascii_length);
	if (status != eap_status_ok)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, status);
	}

	u8_t * const prefix = reinterpret_cast<u8_t *>(debug_buffer->get_data(max_prefix_length));
	u8_t * const ascii = reinterpret_cast<u8_t *>(debug_buffer->get_data_offset(max_prefix_length, ascii_length));

	if (prefix == 0 || ascii == 0)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, eap_status_allocation_error);
	}

	u32_t ind(0ul);
	u32_t offset(0ul);

	status = debug_create_prefix(m_recursion + 1u, prefix, max_prefix_length, &offset);
	if (status != eap_status_ok)
	{
		EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
		return EAP_STATUS_RETURN(m_am_tools, status);
	}

	u32_t init_indentation_offset = offset;
	u32_t type_data_size = get_header_length() + get_content_length();
	u32_t data_ind(0ul);
	u32_t ascii_ind(0ul);
	u8_t octet(0);

	for (ind = m_offset_of_contents_field; ind < type_data_size && ind < m_input_data_length; ++ind)
	{
		offset += m_am_tools->snprintf(
			&prefix[offset],
			max_prefix_length - offset,
			"%02x \0",
			m_input_data[ind]);

		octet = m_input_data[ind];

		if (octet < 0x20 || 0x7e < octet)
		{
			octet = '.';
		}

		m_am_tools->snprintf(
			&ascii[ascii_ind],
			ascii_length - ascii_ind,
			"%c\0",
			octet);

		++data_ind;
		++ascii_ind;

		if ((ascii_ind % COUNT_OF_OCTETS) == 0)
		{
			prefix[offset] = 0;
			ascii[ascii_ind] = 0;

			offset = init_indentation_offset;
			ascii_ind = 0ul;

			EAP_TRACE_DEBUG(
				m_am_tools,
				TRACE_FLAGS_DEFAULT,
				(EAPL("%s |%s|\n"),
					prefix,
					ascii));
		}
	} // for()

	u32_t remainder(ascii_ind % COUNT_OF_OCTETS);

	if (remainder > 0ul)
	{
		for (; ascii_ind < COUNT_OF_OCTETS; ++ascii_ind)
		{
			offset += m_am_tools->snprintf(
				&prefix[offset],
				max_prefix_length - offset,
				"   \0");

			m_am_tools->snprintf(
				&ascii[ascii_ind],
				ascii_length - ascii_ind,
				" \0");
		} // for()

		prefix[offset] = 0;
		ascii[ascii_ind] = 0;

		EAP_TRACE_DEBUG(
			m_am_tools,
			TRACE_FLAGS_DEFAULT,
			(EAPL("%s |%s|\n"),
				prefix,
				ascii));
	}

	EAP_TRACE_END(m_am_tools, TRACE_FLAGS_DEFAULT);
	return EAP_STATUS_RETURN(m_am_tools, status);
}
Exemple #18
0
int
tst_movements(MENU_ARGS)
{
  /* Test of:
     CUF (Cursor Forward)
     CUB (Cursor Backward)
     CUD (Cursor Down)      IND (Index)  NEL (Next Line)
     CUU (Cursor Up)        RI  (Reverse Index)
     CUP (Cursor Position)  HVP (Horizontal and Vertical Position)
     ED  (Erase in Display)
     EL  (Erase in Line)
     DECALN (Screen Alignment Display)
     DECAWM (Autowrap)
     <CR> <BS>
     Cursor control characters inside CSI sequences
   */

  int i, row, col, pass, width, hlfxtra;
  const char *ctext = "This is a correct sentence";

  set_tty_crmod(TRUE);  /* want to disable tab/space conversion */

  for (pass = 0; pass <= 1; pass++) {
    int inner_l, inner_r;

    if (pass == 0) {
      deccolm(FALSE);
      width = min_cols;
    } else {
      deccolm(TRUE);
      width = max_cols;
    }

    /* Compute left/right columns for a 60-column box centered in 'width' */
    inner_l = (width - 60) / 2;
    inner_r = 61 + inner_l;
    hlfxtra = (width - 80) / 2;

    if (LOG_ENABLED)
      fprintf(log_fp, "tst_movements box(%d cols)\n", pass ? max_cols : min_cols);

    decaln();
    cup(9, inner_l);
    ed(1);
    cup(18, 60 + hlfxtra);
    ed(0);
    el(1);
    cup(9, inner_r);
    el(0);
    /* 132: 36..97 */
    /*  80: 10..71 */
    for (row = 10; row <= 16; row++) {
      cup(row, inner_l);
      el(1);
      cup(row, inner_r);
      el(0);
    }
    cup(17, 30);
    el(2);
    for (col = 1; col <= width; col++) {
      hvp(max_lines, col);
      printf("*");
      hvp(1, col);
      printf("*");
    }
    cup(2, 2);
    for (row = 2; row <= max_lines - 1; row++) {
      printf("+");
      cub(1);
      ind();
    }
    cup(max_lines - 1, width - 1);
    for (row = max_lines - 1; row >= 2; row--) {
      printf("+");
      cub(1);
      ri();
    }
    cup(2, 1);
    for (row = 2; row <= max_lines - 1; row++) {
      printf("*");
      cup(row, width);
      printf("*");
      cub(10);
      if (row < 10)
        nel();
      else
        printf("\n");
    }
    cup(2, 10);
    cub(42 + hlfxtra);
    cuf(2);
    for (col = 3; col <= width - 2; col++) {
      printf("+");
      cuf(0);
      cub(2);
      cuf(1);
    }
    cup(max_lines - 1, inner_r - 1);
    cuf(42 + hlfxtra);
    cub(2);
    for (col = width - 2; col >= 3; col--) {
      printf("+");
      cub(1);
      cuf(1);
      cub(0);
      printf("%c", 8);
    }
    cup(1, 1);
    cuu(10);
    cuu(1);
    cuu(0);
    cup(max_lines, width);
    cud(10);
    cud(1);
    cud(0);

    cup(10, 2 + inner_l);
    for (row = 10; row <= 15; row++) {
      for (col = 2 + inner_l; col <= inner_r - 2; col++)
        printf(" ");
      cud(1);
      cub(58);
    }
    cuu(5);
    cuf(1);
    printf("The screen should be cleared,  and have an unbroken bor-");
    cup(12, inner_l + 3);
    printf("der of *'s and +'s around the edge,   and exactly in the");
    cup(13, inner_l + 3);
    printf("middle  there should be a frame of E's around this  text");
    cup(14, inner_l + 3);
    printf("with  one (1) free position around it.    ");
    holdit();
  }
  deccolm(FALSE);

  /* DECAWM demo */
  for (pass = 0; pass <= 1; pass++) {
    static char on_left[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    static char on_right[] = "abcdefghijklmnopqrstuvwxyz";
    int height = sizeof(on_left) - 1;
    int region = max_lines - 6;

    if (LOG_ENABLED)
      fprintf(log_fp, "tst_movements wrap(%d cols)\n", pass ? max_cols : min_cols);

    /* note: DECCOLM clears the screen */
    if (pass == 0) {
      deccolm(FALSE);
      width = min_cols;
    } else {
      deccolm(TRUE);
      width = max_cols;
    }

    println("Test of autowrap, mixing control and print characters.");
    println("The left/right margins should have letters in order:");

    decstbm(3, region + 3);
    decom(TRUE);  /* this also homes the cursor */
    for (i = 0; i < height; ++i) {
      switch (i % 4) {
      case 0:
        /* draw characters as-is, for reference */
        __(cup(region + 1, 1), printf("%c", on_left[i]));
        __(cup(region + 1, width), printf("%c", on_right[i]));
        printf("\n");
        break;
      case 1:
        /* simple wrapping */
        __(cup(region, width), printf("%c%c", on_right[i - 1], on_left[i]));
        /* backspace at right margin */
        __(cup(region + 1, width), printf("%c%c %c",
                                          on_left[i], BS, on_right[i]));
        printf("\n");
        break;
      case 2:
        /* tab to right margin */
        __(cup(region + 1, width), printf("%c%c%c%c%c%c",
                                          on_left[i], BS, BS,
                                          TAB, TAB, on_right[i]));
        __(cup(region + 1, 2), printf("%c%c\n", BS, on_left[i]));
        break;
      default:
        /* newline at right margin */
        __(cup(region + 1, width), printf("\n"));
        __(cup(region, 1), printf("%c", on_left[i]));
        __(cup(region, width), printf("%c", on_right[i]));
        break;
      }
    }
    decom(FALSE);
    decstbm(0, 0);
    cup(max_lines - 2, 1);
    holdit();
  }
  deccolm(FALSE);   /* 80 cols */

  if (LOG_ENABLED)
    fprintf(log_fp, "tst_movements cursor-controls in ESC sequences\n");

  vt_clear(2);
  vt_move(1, 1);
  println("Test of cursor-control characters inside ESC sequences.");
  println("Below should be four identical lines:");
  println("");
  println("A B C D E F G H I");
  for (i = 1; i < 10; i++) {
    printf("%c", '@' + i);
    do_csi("2%cC", BS);   /* Two forward, one backspace */
  }
  println("");
  /* Now put CR in CUF sequence. */
  printf("A ");
  for (i = 2; i < 10; i++)
    printf("%s%c%dC%c", csi_output(), CR, 2 * i - 2, '@' + i);
  println("");
  /* Now put VT in CUU sequence. */
  rm("20");
  for (i = 1; i < 10; i++) {
    printf("%c ", '@' + i);
    do_csi("1\013A");
  }
  println("");
  println("");
  holdit();

  if (LOG_ENABLED)
    fprintf(log_fp, "tst_movements leading zeros in ESC sequences\n");

  vt_clear(2);
  vt_move(1, 1);
  println("Test of leading zeros in ESC sequences.");
  printf("Two lines below you should see the sentence \"%s\".", ctext);
  for (col = 1; *ctext; col++)
    printf("%s00000000004;00000000%dH%c", csi_output(), col, *ctext++);
  cup(20, 1);

  restore_ttymodes();
  return MENU_HOLD;
}
int main(int argc, char **argv) {

  MPI_Init(&argc, &argv); 
  int r,p;
  MPI_Comm comm = MPI_COMM_WORLD;
  MPI_Comm_rank(comm, &r);
  MPI_Comm_size(comm, &p);
  int n, energy, niters;

  if (r==0) {
      // argument checking
      if(argc < 4) {
          if(!r) printf("usage: stencil_mpi <n> <energy> <niters>\n");
          MPI_Finalize();
          exit(1);
      }

      n = atoi(argv[1]); // nxn grid
      energy = atoi(argv[2]); // energy to be injected per iteration
      niters = atoi(argv[3]); // number of iterations
      
      // distribute arguments
      int args[3] = {n, energy, niters};
      MPI_Bcast(args, 3, MPI_INT, 0, comm);
  }
  else {
      int args[3];
      MPI_Bcast(args, 3, MPI_INT, 0, comm);
      n=args[0]; energy=args[1]; niters=args[2];
  }

  int pdims[2]={0,0};
  // compute good (rectangular) domain decomposition
  MPI_Dims_create(p, 2, pdims);
  int px = pdims[0];
  int py = pdims[1];

  // create Cartesian topology
  int periods[2] = {0,0};
  MPI_Comm topocomm;
  MPI_Cart_create(comm, 2, pdims, periods, 0, &topocomm);

  // get my local x,y coordinates
  int coords[2];
  MPI_Cart_coords(topocomm, r, 2, coords);
  int rx = coords[0];
  int ry = coords[1];

  int source, north, south, east, west;
  MPI_Cart_shift(topocomm, 0, 1, &west, &east);
  MPI_Cart_shift(topocomm, 1, 1, &north, &south);

  // decompose the domain
  int bx = n/px; // block size in x
  int by = n/py; // block size in y
  int offx = rx*bx; // offset in x
  int offy = ry*by; // offset in y

  //printf("[%i] (%i,%i) - w: %i, e: %i, n: %i, s: %i x*y: %i x %i\n", r, rx,ry,west,east,north,south, px, py);

  // allocate two work arrays
  double *aold = (double*)calloc(1,(bx+2)*(by+2)*sizeof(double)); // 1-wide halo zones!
  double *anew = (double*)calloc(1,(bx+2)*(by+2)*sizeof(double)); // 1-wide halo zones!
  double *tmp;

  // initialize three heat sources
  #define nsources 3
  int sources[nsources][2] = {{n/2,n/2}, {n/3,n/3}, {n*4/5,n*8/9}};
  int locnsources=0; // number of sources in my area
  int locsources[nsources][2]; // sources local to my rank
  for (int i=0; i<nsources; ++i) { // determine which sources are in my patch
    int locx = sources[i][0] - offx;
    int locy = sources[i][1] - offy;
    if(locx >= 0 && locx < bx && locy >= 0 && locy < by) {
      locsources[locnsources][0] = locx+1; // offset by halo zone
      locsources[locnsources][1] = locy+1; // offset by halo zone
      locnsources++;
    }
  }

  double t=-MPI_Wtime(); // take time
  // create north-south datatype
  MPI_Datatype north_south_type;
  MPI_Type_contiguous(bx, MPI_DOUBLE, &north_south_type);
  MPI_Type_commit(&north_south_type);
  // create east-west type
  MPI_Datatype east_west_type;
  MPI_Type_vector(by,1,bx+2,MPI_DOUBLE, &east_west_type);
  MPI_Type_commit(&east_west_type);

  double heat; // total heat in system
  for(int iter=0; iter<niters; ++iter) {
    // refresh heat sources
    for(int i=0; i<locnsources; ++i) {
      aold[ind(locsources[i][0],locsources[i][1])] += energy; // heat source
    }

    // exchange data with neighbors
    MPI_Request reqs[8];
    MPI_Isend(&aold[ind(1,1)] /* north */, 1, north_south_type, north, 9, topocomm, &reqs[0]);
    MPI_Isend(&aold[ind(1,by)] /* south */, 1, north_south_type, south, 9, topocomm, &reqs[1]);
    MPI_Isend(&aold[ind(bx,1)] /* east */, 1, east_west_type, east, 9, topocomm, &reqs[2]);
    MPI_Isend(&aold[ind(1,1)] /* west */, 1, east_west_type, west, 9, topocomm, &reqs[3]);
    MPI_Irecv(&aold[ind(1,0)] /* north */, 1, north_south_type, north, 9, topocomm, &reqs[4]);
    MPI_Irecv(&aold[ind(1,by+1)] /* south */, 1, north_south_type, south, 9, topocomm, &reqs[5]);
    MPI_Irecv(&aold[ind(bx+1,1)] /* west */, 1, east_west_type, east, 9, topocomm, &reqs[6]);
    MPI_Irecv(&aold[ind(0,1)] /* east */, 1, east_west_type, west, 9, topocomm, &reqs[7]);

    // update inner grid points
    heat = 0.0;
    for(int i=2; i<bx; ++i) {
      for(int j=2; j<by; ++j) {
        anew[ind(i,j)] = anew[ind(i,j)]/2.0 + (aold[ind(i-1,j)] + aold[ind(i+1,j)] + aold[ind(i,j-1)] + aold[ind(i,j+1)])/4.0/2.0;
        heat += anew[ind(i,j)];
      }
    }

    // wait for communication to complete
    MPI_Waitall(8, reqs, MPI_STATUS_IGNORE);

    // update outer grid points
    for(int i=2; i<bx; ++i) { // north, south -- two elements less per row (first and last) to avoid "double computation" in next loop!
      for(int j=1; j < by+1; j+=by-1) {
        anew[ind(i,j)] = anew[ind(i,j)]/2.0 + (aold[ind(i-1,j)] + aold[ind(i+1,j)] + aold[ind(i,j-1)] + aold[ind(i,j+1)])/4.0/2.0;
        heat += anew[ind(i,j)];
      }
    }

    // update outer grid points
    for(int i=1; i<bx+1; i+=bx-1) { // east, west -- full columns
      for(int j=1; j < by+1; ++j) {
        anew[ind(i,j)] = anew[ind(i,j)]/2.0 + (aold[ind(i-1,j)] + aold[ind(i+1,j)] + aold[ind(i,j-1)] + aold[ind(i,j+1)])/4.0/2.0;
        heat += anew[ind(i,j)];
      }
    }

    // swap arrays
    tmp=anew; anew=aold; aold=tmp; // swap arrays
    
    // optional - print image
  	if(iter == niters-1) printarr_par(iter, anew, n, px, py, rx, ry, bx, by, offx, offy, comm);
  }
  t+=MPI_Wtime();
  
  // get final heat in the system
  double rheat;
  MPI_Allreduce(&heat, &rheat, 1, MPI_DOUBLE, MPI_SUM, comm);
  if(!r) printf("[%i] last heat: %f time: %f\n", r, rheat, t);

  MPI_Finalize();
}
Exemple #20
0
void DESIGN_mrf::init_data(const datamatrix & dm, const datamatrix & iv)
  {

  if (ma.get_bandsize() > 40)
    ma.reorderopt();

  ma.compute_reg(dm,posbeg,posend,effectvalues,index_data);

  vector<ST::string> errormessages = ma.get_errormessages();
  if (errormessages.size() >= 1)
    {

    errors=true;
    unsigned i;
    for (i=0;i<errormessages.size();i++)
      optionsp->out(errormessages[i]);
    }

  if (errors==false)
    {
    vector<int> posbeg_help = posbeg;
    vector<int> posend_help = posend;
    vector<ST::string> effectvalues_help = effectvalues;

    DESIGN::init_data(dm,iv);

    posbeg = posbeg_help;
    posend = posend_help;
    effectvalues = effectvalues_help;

    int k,j;
    int * workindex = index_data.getV();
    ind = statmatrix<unsigned>(dm.rows(),1);
    for (j=0;j<posend.size();j++)
      {

      if (posbeg[j] != -1)
        {
        for (k=posbeg[j];k<=posend[j];k++,workindex++)
          ind(*workindex,0) = j;
        }
      else
        {
        optionsp->out("NOTE: no observations for region " + effectvalues[j] + "\n");
        }

      }


    // TEST
    /*
    int j;
    ofstream out2("c:\\bayesx\\testh\\results\\posend_neu.res");
    for (j=0;j<posend.size();j++)
      out2 << posend[j] << endl;

    ofstream out2a("c:\\bayesx\\testh\\results\\posbeg_neu.res");
    for (j=0;j<posbeg.size();j++)
      out2a << posbeg[j] << endl;

    ofstream out3("c:\\bayesx\\testh\\results\\effectvalues_neu.res");
    for (j=0;j<effectvalues.size();j++)
      out3 << effectvalues[j] << endl;

    ofstream out4("c:\\bayesx\\testh\\results\\index_data_neu.res");
    index_data.prettyPrint(out4);
    */
    // TEST


    meaneffectnr = compute_modecategorie();

    if (ma.get_errormessages().size() > 0)
      {
      //  FEHLT!!
      }

    } // end: if (errors==false)

  }
void QPlaneStress2d :: drawScalar(oofegGraphicContext &context)
{
    int i, indx,  n [ 4 ], result = 0;
    WCRec p [ 4 ], pp [ 9 ];
    GraphicObj *tr;
    TimeStep *tStep = this->giveDomain()->giveEngngModel()->giveCurrentStep();
    FloatArray v [ 8 ];
    double s [ 9 ], ss [ 4 ], defScale;
    int ip;
    GaussPoint *gp;

    if ( !context.testElementGraphicActivity(this) ) {
        return;
    }

    EASValsSetLayer(OOFEG_VARPLOT_PATTERN_LAYER);
    if ( context.giveIntVarMode() == ISM_recovered ) {
        // ============ plot the recovered values (smoothed data) ===============
        for ( i = 1; i <= 8; i++ ) {
            result += this->giveInternalStateAtNode(v [ i - 1 ], context.giveIntVarType(), context.giveIntVarMode(), i, tStep);
        }

        if ( result != 8 ) {
            return;
        }

        indx = context.giveIntVarIndx();

        for ( i = 1; i <= 8; i++ ) {
            s [ i - 1 ] = v [ i - 1 ].at(indx);
        }

        // auxiliary value at an added central node
        // computed as average of the values at all Gauss points

        s [ 8 ] = 0.;
        for ( ip = 1; ip <= integrationRulesArray [ 0 ]->giveNumberOfIntegrationPoints(); ip++ ) {
            gp = integrationRulesArray [ 0 ]->getIntegrationPoint(ip - 1);
            if ( giveIPValue(v [ 0 ], gp, context.giveIntVarType(), tStep) == 0 ) {
                return;
            }

            s [ 8 ] +=  v [ 0 ].at(indx);
        }

        s [ 8 ] /= integrationRulesArray [ 0 ]->giveNumberOfIntegrationPoints();
        //s[8] = (s[4]+s[5]+s[6]+s[7])/4.;

        for ( i = 0; i < 8; i++ ) {
            if ( context.getInternalVarsDefGeoFlag() ) {
                // use deformed geometry
                defScale = context.getDefScale();
                pp [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(1, tStep, defScale);
                pp [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(2, tStep, defScale);
                pp [ i ].z = 0.;
            } else {
                // use initial geometry
                pp [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(1);
                pp [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(2);
                pp [ i ].z = 0.;
            }
        }

        pp [ 8 ].x = ( pp [ 4 ].x + pp [ 5 ].x + pp [ 6 ].x + pp [ 7 ].x ) / 4.;
        pp [ 8 ].y = ( pp [ 4 ].y + pp [ 5 ].y + pp [ 6 ].y + pp [ 7 ].y ) / 4.;
        pp [ 8 ].z = 0.;


        for ( int t = 1; t <= 4; t++ ) {
            if ( t == 1 ) {
                n [ 0 ] = 0;
                n [ 1 ] = 4;
                n [ 2 ] = 8;
                n [ 3 ] = 7;
            } else if ( t == 2 ) {
                n [ 0 ] = 4;
                n [ 1 ] = 1;
                n [ 2 ] = 5;
                n [ 3 ] = 8;
            } else if ( t == 3 ) {
                n [ 0 ] = 5;
                n [ 1 ] = 2;
                n [ 2 ] = 6;
                n [ 3 ] = 8;
            } else {
                n [ 0 ] = 6;
                n [ 1 ] = 3;
                n [ 2 ] = 7;
                n [ 3 ] = 8;
            }

            ss [ 0 ] = s [ n [ 0 ] ];
            ss [ 1 ] = s [ n [ 1 ] ];
            ss [ 2 ] = s [ n [ 2 ] ];
            ss [ 3 ] = s [ n [ 3 ] ];


            for ( i = 0; i < 4; i++ ) {
                p [ i ].x = pp [ n [ i ] ].x;
                p [ i ].y = pp [ n [ i ] ].y;
                p [ i ].z = 0.;
            }

            if ( context.getScalarAlgo() == SA_ISO_SURF ) {
                /*
                 * for ( i = 0; i < 4; i++ ) {
                 *    if ( context.getInternalVarsDefGeoFlag() ) {
                 *        // use deformed geometry
                 *        defScale = context.getDefScale();
                 *        p [ i ].x = ( FPNum ) this->giveNode(n[i] + 1)->giveUpdatedCoordinate(1, tStep, defScale);
                 *        p [ i ].y = ( FPNum ) this->giveNode(n[i] + 1)->giveUpdatedCoordinate(2, tStep, defScale);
                 *        p [ i ].z = 0.;
                 *    } else {
                 *        // use initial geometry
                 *        p [ i ].x = ( FPNum ) this->giveNode(n[i] + 1)->giveCoordinate(1);
                 *        p [ i ].y = ( FPNum ) this->giveNode(n[i] + 1)->giveCoordinate(2);
                 *        p [ i ].z = 0.;
                 *    }
                 * }
                 */
                //EASValsSetColor(gc.getYieldPlotColor(ratio));
                context.updateFringeTableMinMax(ss, 4);
                tr =  CreateQuadWD3D(p, ss [ 0 ], ss [ 1 ], ss [ 2 ], ss [ 3 ]);
                EGWithMaskChangeAttributes(LAYER_MASK, tr);
                EMAddGraphicsToModel(ESIModel(), tr);
            } else if ( ( context.getScalarAlgo() == SA_ZPROFILE ) || ( context.getScalarAlgo() == SA_COLORZPROFILE ) ) {
                //double landScale = context.getLandScale();

                for ( i = 0; i < 4; i++ ) {
                    /*
                     * if ( context.getInternalVarsDefGeoFlag() ) {
                     *    // use deformed geometry
                     *    defScale = context.getDefScale();
                     *    p [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(1, tStep, defScale);
                     *    p [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(2, tStep, defScale);
                     *    p [ i ].z = ss [ i ] * landScale;
                     * } else {
                     *    // use initial geometry
                     *    p [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(1);
                     *    p [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(2);
                     *    p [ i ].z = ss [ i ] * landScale;
                     * }
                     */

                    // this fixes a bug in ELIXIR
                    if ( fabs(ss [ i ]) < 1.0e-6 ) {
                        ss [ i ] = 1.0e-6;
                    }
                }

                if ( context.getScalarAlgo() == SA_ZPROFILE ) {
                    EASValsSetColor( context.getDeformedElementColor() );
                    EASValsSetLineWidth(OOFEG_DEFORMED_GEOMETRY_WIDTH);
                    tr =  CreateQuad3D(p);
                    EGWithMaskChangeAttributes(WIDTH_MASK | COLOR_MASK | LAYER_MASK, tr);
                } else {
                    context.updateFringeTableMinMax(s, 4);
                    tr =  CreateQuadWD3D(p, ss [ 0 ], ss [ 1 ], ss [ 2 ], ss [ 3 ]);
                    EGWithMaskChangeAttributes(LAYER_MASK, tr);
                }

                EMAddGraphicsToModel(ESIModel(), tr);
            }
        }
    } else if ( context.giveIntVarMode() == ISM_local ) {
        // ========== plot the local values (raw data) =====================
        if ( numberOfGaussPoints != 4 ) {
            return;
        }

        IntArray ind(4);
        FloatArray *gpCoords;
        WCRec pp [ 9 ];

        for ( i = 0; i < 8; i++ ) {
            if ( context.getInternalVarsDefGeoFlag() ) {
                // use deformed geometry
                defScale = context.getDefScale();
                pp [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(1, tStep, defScale);
                pp [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(2, tStep, defScale);
                pp [ i ].z = 0.;
            } else {
                pp [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(1);
                pp [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(2);
                pp [ i ].z = 0.;
            }
        }

        pp [ 8 ].x = 0.25 * ( pp [ 0 ].x + pp [ 1 ].x + pp [ 2 ].x + pp [ 3 ].x );
        pp [ 8 ].y = 0.25 * ( pp [ 0 ].y + pp [ 1 ].y + pp [ 2 ].y + pp [ 3 ].y );
        pp [ 8 ].z = 0.;

        for ( ip = 1; ip <= integrationRulesArray [ 0 ]->giveNumberOfIntegrationPoints(); ip++ ) {
            gp = integrationRulesArray [ 0 ]->getIntegrationPoint(ip - 1);
            gpCoords = gp->giveCoordinates();
            if ( ( gpCoords->at(1) > 0. ) && ( gpCoords->at(2) > 0. ) ) {
                ind.at(1) = 0;
                ind.at(2) = 4;
                ind.at(3) = 8;
                ind.at(4) = 7;
            } else if ( ( gpCoords->at(1) < 0. ) && ( gpCoords->at(2) > 0. ) ) {
                ind.at(1) = 4;
                ind.at(2) = 1;
                ind.at(3) = 5;
                ind.at(4) = 8;
            } else if ( ( gpCoords->at(1) < 0. ) && ( gpCoords->at(2) < 0. ) ) {
                ind.at(1) = 5;
                ind.at(2) = 2;
                ind.at(3) = 6;
                ind.at(4) = 8;
            } else {
                ind.at(1) = 6;
                ind.at(2) = 3;
                ind.at(3) = 7;
                ind.at(4) = 8;
            }

            if ( giveIPValue(v [ 0 ], gp, context.giveIntVarType(), tStep) == 0 ) {
                return;
            }

            indx = context.giveIntVarIndx();

            for ( i = 1; i <= 4; i++ ) {
                s [ i - 1 ] = v [ 0 ].at(indx);
            }

            for ( i = 0; i < 4; i++ ) {
                p [ i ].x = pp [ ind.at(i + 1) ].x;
                p [ i ].y = pp [ ind.at(i + 1) ].y;
                p [ i ].z = pp [ ind.at(i + 1) ].z;
            }

            context.updateFringeTableMinMax(s, 4);
            tr =  CreateQuadWD3D(p, s [ 0 ], s [ 1 ], s [ 2 ], s [ 3 ]);
            EGWithMaskChangeAttributes(LAYER_MASK, tr);
            EMAddGraphicsToModel(ESIModel(), tr);
        }
    }
}
Exemple #22
0
void L4Axisymm :: drawScalar(oofegGraphicContext &context)
{
    int i, indx, result = 0;
    WCRec p [ 4 ];
    GraphicObj *tr;
    TimeStep *tStep = this->giveDomain()->giveEngngModel()->giveCurrentStep();
    FloatArray v [ 4 ];
    double s [ 4 ], defScale;
    IntArray map;

    if ( !context.testElementGraphicActivity(this) ) {
        return;
    }

    EASValsSetLayer(OOFEG_VARPLOT_PATTERN_LAYER);
    if ( context.giveIntVarMode() == ISM_recovered ) {
        for ( i = 1; i <= 4; i++ ) {
            result += this->giveInternalStateAtNode(v [ i - 1 ], context.giveIntVarType(), context.giveIntVarMode(), i, tStep);
        }

        if ( result != 4 ) {
            return;
        }

        result = this->giveIntVarCompFullIndx( map, context.giveIntVarType() );
        if ( ( !result ) || ( indx = map.at( context.giveIntVarIndx() ) ) == 0 ) {
            return;
        }

        for ( i = 1; i <= 4; i++ ) {
            s [ i - 1 ] = v [ i - 1 ].at(indx);
        }

        if ( context.getScalarAlgo() == SA_ISO_SURF ) {
            for ( i = 0; i < 4; i++ ) {
                if ( context.getInternalVarsDefGeoFlag() ) {
                    // use deformed geometry
                    defScale = context.getDefScale();
                    p [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(1, tStep, EID_MomentumBalance, defScale);
                    p [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(2, tStep, EID_MomentumBalance, defScale);
                    p [ i ].z = 0.;
                } else {
                    p [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(1);
                    p [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(2);
                    p [ i ].z = 0.;
                }
            }

            //EASValsSetColor(gc.getYieldPlotColor(ratio));
            context.updateFringeTableMinMax(s, 4);
            tr =  CreateQuadWD3D(p, s [ 0 ], s [ 1 ], s [ 2 ], s [ 3 ]);
            EGWithMaskChangeAttributes(LAYER_MASK, tr);
            EMAddGraphicsToModel(ESIModel(), tr);

            /*
             * } else if (context.getScalarAlgo() == SA_ISO_LINE) {
             *
             * EASValsSetColor(context.getActiveCrackColor());
             * EASValsSetLineWidth(OOFEG_ISO_LINE_WIDTH);
             *
             * for (i=0; i< 4; i++) {
             * if (context.getInternalVarsDefGeoFlag()) {
             * // use deformed geometry
             * defScale = context.getDefScale();
             * p[i].x = (FPNum) this->giveNode(i+1)->giveUpdatedCoordinate(1,tStep,EID_MomentumBalance,defScale);
             * p[i].y = (FPNum) this->giveNode(i+1)->giveUpdatedCoordinate(2,tStep,EID_MomentumBalance,defScale);
             * p[i].z = 0.;
             *
             * } else {
             * p[i].x = (FPNum) this->giveNode(i+1)->giveCoordinate(1);
             * p[i].y = (FPNum) this->giveNode(i+1)->giveCoordinate(2);
             * p[i].z = 0.;
             * }
             * }
             *
             * // isoline implementation
             * oofeg_drawIsoLinesOnQuad (p, s);
             *
             */
        }
    } else if ( context.giveIntVarMode() == ISM_local ) {
        if ( numberOfGaussPoints != 4 ) {
            return;
        }

        int ip;
        GaussPoint *gp;
        IntArray ind(4);
        FloatArray *gpCoords;
        WCRec pp [ 9 ];

        for ( i = 0; i < 4; i++ ) {
            if ( context.getInternalVarsDefGeoFlag() ) {
                // use deformed geometry
                defScale = context.getDefScale();
                pp [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(1, tStep, EID_MomentumBalance, defScale);
                pp [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(2, tStep, EID_MomentumBalance, defScale);
                pp [ i ].z = 0.;
            } else {
                pp [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(1);
                pp [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(2);
                pp [ i ].z = 0.;
            }
        }

        for ( i = 0; i < 3; i++ ) {
            pp [ i + 4 ].x = 0.5 * ( pp [ i ].x + pp [ i + 1 ].x );
            pp [ i + 4 ].y = 0.5 * ( pp [ i ].y + pp [ i + 1 ].y );
            pp [ i + 4 ].z = 0.5 * ( pp [ i ].z + pp [ i + 1 ].z );
        }

        pp [ 7 ].x = 0.5 * ( pp [ 3 ].x + pp [ 0 ].x );
        pp [ 7 ].y = 0.5 * ( pp [ 3 ].y + pp [ 0 ].y );
        pp [ 7 ].z = 0.5 * ( pp [ 3 ].z + pp [ 0 ].z );

        pp [ 8 ].x = 0.25 * ( pp [ 0 ].x + pp [ 1 ].x + pp [ 2 ].x + pp [ 3 ].x );
        pp [ 8 ].y = 0.25 * ( pp [ 0 ].y + pp [ 1 ].y + pp [ 2 ].y + pp [ 3 ].y );
        pp [ 8 ].z = 0.25 * ( pp [ 0 ].z + pp [ 1 ].z + pp [ 2 ].z + pp [ 3 ].z );

        for ( ip = 1; ip <= numberOfGaussPoints; ip++ ) {
            gp = integrationRulesArray [ 0 ]->getIntegrationPoint(ip - 1);
            gpCoords = gp->giveCoordinates();
            if ( ( gpCoords->at(1) > 0. ) && ( gpCoords->at(2) > 0. ) ) {
                ind.at(1) = 0;
                ind.at(2) = 4;
                ind.at(3) = 8;
                ind.at(4) = 7;
            } else if ( ( gpCoords->at(1) < 0. ) && ( gpCoords->at(2) > 0. ) ) {
                ind.at(1) = 4;
                ind.at(2) = 1;
                ind.at(3) = 5;
                ind.at(4) = 8;
            } else if ( ( gpCoords->at(1) < 0. ) && ( gpCoords->at(2) < 0. ) ) {
                ind.at(1) = 5;
                ind.at(2) = 2;
                ind.at(3) = 6;
                ind.at(4) = 8;
            } else {
                ind.at(1) = 6;
                ind.at(2) = 3;
                ind.at(3) = 7;
                ind.at(4) = 8;
            }

            if ( giveIPValue(v [ 0 ], gp, context.giveIntVarType(), tStep) == 0 ) {
                return;
            }

            this->giveIntVarCompFullIndx( map, context.giveIntVarType() );
            if ( ( indx = map.at( context.giveIntVarIndx() ) ) == 0 ) {
                return;
            }

            for ( i = 1; i <= 4; i++ ) {
                s [ i - 1 ] = v [ 0 ].at(indx);
            }

            for ( i = 0; i < 4; i++ ) {
                p [ i ].x = pp [ ind.at(i + 1) ].x;
                p [ i ].y = pp [ ind.at(i + 1) ].y;
                p [ i ].z = pp [ ind.at(i + 1) ].z;
            }

            context.updateFringeTableMinMax(s, 4);
            tr =  CreateQuadWD3D(p, s [ 0 ], s [ 1 ], s [ 2 ], s [ 3 ]);
            EGWithMaskChangeAttributes(LAYER_MASK, tr);
            EMAddGraphicsToModel(ESIModel(), tr);
        }
    }
}
Exemple #23
0
/*
 *
 *  reimplement c++ version of inPolygon_c
 *  indices are allocated within gating function, so it is up to caller to free it
 *  and now it is freed in destructor of its owner "nodeProperties" object
 */
vector<bool> polygonGate::gating(flowData & fdata){




	vector<coordinate> vertices=param.getVertices();
	unsigned nVertex=vertices.size();

	string x=param.xName();
	string y=param.yName();
	valarray<double> xdata(fdata.subset(x));
	valarray<double> ydata(fdata.subset(y));

	unsigned nEvents=xdata.size();
	//init the indices
	vector<bool> ind(nEvents);


	unsigned counter;
	double xinters;
	double p1x, p2x, p1y, p2y;

	for(unsigned i=0; i<nEvents; i++)
	{//iterate over points
	p1x=vertices.at(0).x;
	p1y=vertices.at(0).y;
	counter=0;
	for(unsigned j=1; j <= nVertex; j++)
	{// iterate over vertices
	  /*p1x,p1y and p2x,p2y are the endpoints of the current vertex*/
	  if (j == nVertex)
	  {//the last vertice must "loop around"
		p2x = vertices.at(0).x;
		p2y = vertices.at(0).y;
	  }
	  else
	  {
		p2x = vertices.at(j).x;
		p2y = vertices.at(j).y;
	  }
	  /*if horizontal ray is in range of vertex find the x coordinate where
		ray and vertex intersect*/
	  if(ydata[i] >= min(p1y, p2y) && ydata[i] < max(p1y, p2y) &&xdata[i] <= max(p1x, p2x))
	  {
		  xinters = (ydata[i]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x;
		/*if intersection x coordinate == point x coordinate it lies on the
		  boundary of the polygon, which means "in"*/
		if(xinters==xdata[i])
		{
		  counter=1;
		  break;
		}
		/*count how many vertices are passed by the ray*/
		if (xinters > xdata[i])counter++;
	  }
	  p1x=p2x;
	  p1y=p2y;
	}
	/*uneven number of vertices passed means "in"*/

	ind[i]=((counter % 2) != 0);

	}
	if(isNegate())
		ind.flip();
	return ind;
}
Exemple #24
0
int main(int argc, char **argv) {

  MPI_Init(&argc, &argv); 
  int r,p;
  MPI_Comm comm = MPI_COMM_WORLD;
  MPI_Comm_rank(comm, &r);
  MPI_Comm_size(comm, &p);
  int n, energy, niters, px, py;

   if (r==0) {
       // argument checking
       if(argc < 6) {
           if(!r) printf("usage: stencil_mpi <n> <energy> <niters> <px> <py>\n");
           MPI_Finalize();
           exit(1);
       }

       n = atoi(argv[1]); // nxn grid
       energy = atoi(argv[2]); // energy to be injected per iteration
       niters = atoi(argv[3]); // number of iterations
       px=atoi(argv[4]); // 1st dim processes
       py=atoi(argv[5]); // 2nd dim processes

       if(px * py != p) MPI_Abort(comm, 1);// abort if px or py are wrong
       if(n % py != 0) MPI_Abort(comm, 2); // abort px needs to divide n
       if(n % px != 0) MPI_Abort(comm, 3); // abort py needs to divide n
       
       // distribute arguments
       int args[5] = {n, energy, niters, px,  py};
       MPI_Bcast(args, 5, MPI_INT, 0, comm);
   }
  else {
      int args[5];
      MPI_Bcast(args, 5, MPI_INT, 0, comm);
      n=args[0]; energy=args[1]; niters=args[2]; px=args[3]; py=args[4];
  }

  // determine my coordinates (x,y) -- r=x*a+y in the 2d processor array
  int rx = r % px;
  int ry = r / px;
  // determine my four neighbors
  int north = (ry-1)*px+rx; if(ry-1 < 0)   north = MPI_PROC_NULL;
  int south = (ry+1)*px+rx; if(ry+1 >= py) south = MPI_PROC_NULL;
  int west= ry*px+rx-1;     if(rx-1 < 0)   west = MPI_PROC_NULL;
  int east = ry*px+rx+1;    if(rx+1 >= px) east = MPI_PROC_NULL;
  // decompose the domain
  int bx = n/px; // block size in x
  int by = n/py; // block size in y
  int offx = rx*bx; // offset in x
  int offy = ry*by; // offset in y

  //printf("%i (%i,%i) - w: %i, e: %i, n: %i, s: %i\n", r, ry,rx,west,east,north,south);

  // allocate two work arrays
  double *aold = (double*)calloc(1,(bx+2)*(by+2)*sizeof(double)); // 1-wide halo zones!
  double *anew = (double*)calloc(1,(bx+2)*(by+2)*sizeof(double)); // 1-wide halo zones!
  double *tmp;

  // initialize three heat sources
  #define nsources 3
  int sources[nsources][2] = {{n/2,n/2}, {n/3,n/3}, {n*4/5,n*8/9}};
  int locnsources=0; // number of sources in my area
  int locsources[nsources][2]; // sources local to my rank
  for (int i=0; i<nsources; ++i) { // determine which sources are in my patch
    int locx = sources[i][0] - offx;
    int locy = sources[i][1] - offy;
    if(locx >= 0 && locx < bx && locy >= 0 && locy < by) {
      locsources[locnsources][0] = locx+1; // offset by halo zone
      locsources[locnsources][1] = locy+1; // offset by halo zone
      locnsources++;
    }
  }

  double t=-MPI_Wtime(); // take time
  // create north-south datatype
  MPI_Datatype north_south_type;
  MPI_Type_contiguous(bx, MPI_DOUBLE, &north_south_type);
  MPI_Type_commit(&north_south_type);
  // create east-west type
  MPI_Datatype east_west_type;
  MPI_Type_vector(by,1,bx+2,MPI_DOUBLE, &east_west_type);
  MPI_Type_commit(&east_west_type);

  double heat; // total heat in system
  for(int iter=0; iter<niters; ++iter) {
    // refresh heat sources
    for(int i=0; i<locnsources; ++i) {
      aold[ind(locsources[i][0],locsources[i][1])] += energy; // heat source
    }

    // exchange data with neighbors
    MPI_Request reqs[8];
    MPI_Isend(&aold[ind(1,1)] /* north */, 1, north_south_type, north, 9, comm, &reqs[0]);
    MPI_Isend(&aold[ind(1,by)] /* south */, 1, north_south_type, south, 9, comm, &reqs[1]);
    MPI_Isend(&aold[ind(bx,1)] /* east */, 1, east_west_type, east, 9, comm, &reqs[2]);
    MPI_Isend(&aold[ind(1,1)] /* west */, 1, east_west_type, west, 9, comm, &reqs[3]);
    MPI_Irecv(&aold[ind(1,0)] /* north */, 1, north_south_type, north, 9, comm, &reqs[4]);
    MPI_Irecv(&aold[ind(1,by+1)] /* south */, 1, north_south_type, south, 9, comm, &reqs[5]);
    MPI_Irecv(&aold[ind(bx+1,1)] /* west */, 1, east_west_type, east, 9, comm, &reqs[6]);
    MPI_Irecv(&aold[ind(0,1)] /* east */, 1, east_west_type, west, 9, comm, &reqs[7]);
    MPI_Waitall(8, reqs, MPI_STATUS_IGNORE);

    // update grid points
    heat = 0.0;
    for(int i=1; i<bx+1; ++i) {
      for(int j=1; j<by+1; ++j) {
        anew[ind(i,j)] = anew[ind(i,j)]/2.0 + (aold[ind(i-1,j)] + aold[ind(i+1,j)] + aold[ind(i,j-1)] + aold[ind(i,j+1)])/4.0/2.0;
        heat += anew[ind(i,j)];
      }
    }

    // swap arrays
    tmp=anew; anew=aold; aold=tmp;

    // optional - print image
    if(iter == niters-1) printarr_par(iter, anew, n, px, py, rx, ry, bx, by, offx, offy, comm);
  }
  t+=MPI_Wtime();

  MPI_Type_free(&east_west_type);
  MPI_Type_free(&north_south_type);

  // get final heat in the system
  double rheat;
  MPI_Allreduce(&heat, &rheat, 1, MPI_DOUBLE, MPI_SUM, comm);
  if(!r) printf("[%i] last heat: %f time: %f\n", r, rheat, t);

  MPI_Finalize();
}
Exemple #25
0
// -----------------------------------------------------------------------------
// CBerTlv::TlvByTagValueMulti
// Find several TLVs by tag value. It is assumed that TLVs are sequential. aTlv
// is set to point to TLV sequence. If no tags are found return KErrNotFound
// else KErrNone.
// -----------------------------------------------------------------------------
//
EXPORT_C TInt CBerTlv::TlvByTagValueMulti
(
    CTlv* aTlv,                 // TLV to fill
    TUint8 aTlvTagValue         // Tag of TLV to find
)
{
    OstTraceDef0(OST_TRACE_CATEGORY_DEBUG, TRACE_BORDER, CBERTLV_TLVBYTAGVALUEMULTI_1, "UTILITY: CBerTlv::TlvByTagValueMulti");
    TInt currentTlv( 0 );
    TInt16 tlvLength( 0 );
    TInt indMulti( 0 );
    TInt16 multiLength( 0 );
    // TLV start index
    TInt ind( KCommonTlvHeaderLength );
    TUint8 berTlvLength;
    // First determine if the length of the BerTLV is coded with 1 or 2 bytes.
    if ( KTwoByteLengthCoding == iData[KTlvLengthStartPosition] )
    {
        berTlvLength = iData[KTlvLengthStartPosition + 1];
        ind = ind + 1;
    }
    else
    {
        berTlvLength = iData[KTlvLengthStartPosition];
    }

    for ( TInt i = 0; i < berTlvLength; i+= tlvLength )
    {
        // First determine if the length of the TLV is coded with 1 or 2 bytes.
        if ( KTwoByteLengthCoding == iData[ind + 1] )
        {
            // Length is coded with 2 bytes -> real length is in second byte.
            // first byte is 81 and it is tag for 2 byte length coding.
            tlvLength = static_cast<TInt16>( iData[ind + 0x02] +
                                             KTlvHeaderLength + 1 );
        }
        else
        {
            // TLV header bytes (2) must be added to total length
            tlvLength = static_cast<TInt16>( iData[ind + 1]  +
                                             KTlvHeaderLength );
        }

        currentTlv = iData[ind]&KTagValueMask;

        // Check if TLV in current index is the one that we are searching for
        if ( aTlvTagValue == currentTlv && multiLength == 0x00 )
        {
            // Save first tag position
            indMulti = ind;
            multiLength = tlvLength;
        }
        // Add length
        if ( aTlvTagValue == currentTlv && indMulti != ind )
        {
            multiLength = static_cast<TInt16>( multiLength + tlvLength );
        }

        // If last tag, return
        if ( (i + tlvLength) >= berTlvLength )
        {
            TPtrC8 data = ( iData.Mid( indMulti , multiLength ) );
            aTlv->SetData( data );
            break;
        }
        ind += tlvLength;
    }

    if( 0 == indMulti)
    {
        return KErrNotFound;
    }
    else
    {
        return KErrNone;
    }
}
Exemple #26
0
void genotype::read_genotypes (string filename) { 
	ifstream inp (filename.c_str());
	if (!inp.is_open()){
		cerr << "Error reading file "<< filename <<endl;
		exit(1);
	}
	string line;
	int linenum  = 0;
	int chrindex = 0;
	int snpindex = 0;
	bool setind = false;
	while ( std::getline (inp, line)){
		linenum ++;
		char c = line[0];
		if (c=='#')
			continue;
		
		if (line.empty())
			continue;

		vector<snp> &sv = snps[chrs[chrindex]];
		vector<int> &gtype = sv[snpindex].gtype;
		io::println ("Length = "  + tostring(line.length()),4);
		int vc = 0;
		int rc = 0;

		if (!givenind ) { 
			if (!setind){
				nind = line.length();
				for (int i  =0 ;i  < nind; i++){
					string id = tostring(i);
					indiv.push_back (ind (id, 'U', "G"));
				}
				setind = true;
			} else {
				if (nind != line.length()) {
					cerr << "Bad genotype in " << filename << ": Line "<< linenum  << endl;
					exit(1);
				}
			}
			gtype.resize(nind,9);
		} else { 
			if (nind != line.length()) {
				cerr << "Bad genotype in " << filename << ": Line "<< linenum  << endl;
				exit(1);
			}
		}

		for (int i = 0 ; i < line.length();i++){
			char c = line.at(i);
//			gtype[i] = atoi (&c);
			gtype[i] = c-48;
			if (gtype[i]==9 || (gtype[i]>=0 && gtype[i]<=2)){
				if (!isgenotype && gtype[i]==2) {
					cerr << "Data is not haploid in " << filename << ": Line "<< linenum <<", col = " << i << endl;
				}
				if (gtype[i]!=9) {
					vc += gtype[i];
					rc = isgenotype?2:1;
					rc = rc - gtype[i];
				}
			} else {
				cerr << "Bad genotype in " << filename << ": Line "<< linenum <<", col = " << i << endl;
				exit(1);
			}
			if ( io::debug >= 4) {
				cout << "gtype " << tostring(i) << "  = " << tostring (c) << "," << tostring (gtype[i])<<endl;
			}
		}
		sv[snpindex].vcount = vc;
		sv[snpindex].rcount = rc;
		sv[snpindex].freq = vc+rc==0? 0:((double)vc)/(vc+rc);

		snpindex ++;	
		if (snpindex < sv.size()){}
		else {
			snpindex = 0 ;
			chrindex++;
		}
		
	}	
	inp.close();

	if (io::debug >= 3) { 
		for (int i = 0  ; i < nchr; i++){
			vector<snp> &tmpsnps = snps[chrs[i]];
			for (int j =  0 ; j < tmpsnps.size();j++){
				cout << tmpsnps[j].getgtype () << endl;
			}
			cout << endl;
		}	
	}
}
void QPlaneStrain :: drawScalar(oofegGraphicContext &context)
{
    int i, indx;
    WCRec p [ 4 ];
    GraphicObj *tr;
    TimeStep *tStep = this->giveDomain()->giveEngngModel()->giveCurrentStep();
    FloatArray v [ 4 ];
    double s [ 4 ], defScale;

    if ( !context.testElementGraphicActivity(this) ) {
        return;
    }

    EASValsSetLayer(OOFEG_VARPLOT_PATTERN_LAYER);
    if ( context.giveIntVarMode() == ISM_recovered ) {
        // ============ plot the recovered values (smoothed data) ===============
        /*
         * for ( i = 1; i <= 4; i++ ) {
         *    result += this->giveInternalStateAtNode(v [ i - 1 ], context.giveIntVarType(), context.giveIntVarMode(), i, tStep);
         * }
         *
         * if ( result != 4 ) {
         *    return;
         * }
         *
         * indx = context.giveIntVarIndx();
         *
         * for ( i = 1; i <= 4; i++ ) {
         *    s [ i - 1 ] = v [ i - 1 ].at(indx);
         * }
         *
         * if ( context.getScalarAlgo() == SA_ISO_SURF ) {
         *    for ( i = 0; i < 4; i++ ) {
         *        if ( context.getInternalVarsDefGeoFlag() ) {
         *            // use deformed geometry
         *            defScale = context.getDefScale();
         *            p [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(1, tStep, defScale);
         *            p [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(2, tStep, defScale);
         *            p [ i ].z = 0.;
         *        } else {
         *            p [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(1);
         *            p [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(2);
         *            p [ i ].z = 0.;
         *        }
         *    }
         *
         *    //EASValsSetColor(gc.getYieldPlotColor(ratio));
         *    context.updateFringeTableMinMax(s, 4);
         *    tr =  CreateQuadWD3D(p, s [ 0 ], s [ 1 ], s [ 2 ], s [ 3 ]);
         *    EGWithMaskChangeAttributes(LAYER_MASK, tr);
         *    EMAddGraphicsToModel(ESIModel(), tr);
         * } else if ( ( context.getScalarAlgo() == SA_ZPROFILE ) || ( context.getScalarAlgo() == SA_COLORZPROFILE ) ) {
         *    double landScale = context.getLandScale();
         *
         *    for ( i = 0; i < 4; i++ ) {
         *        if ( context.getInternalVarsDefGeoFlag() ) {
         *            // use deformed geometry
         *            defScale = context.getDefScale();
         *            p [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(1, tStep, defScale);
         *            p [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(2, tStep, defScale);
         *            p [ i ].z = s [ i ] * landScale;
         *        } else {
         *            p [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(1);
         *            p [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(2);
         *            p [ i ].z = s [ i ] * landScale;
         *        }
         *
         *        // this fixes a bug in ELIXIR
         *        if ( fabs(s [ i ]) < 1.0e-6 ) {
         *            s [ i ] = 1.0e-6;
         *        }
         *    }
         *
         *    if ( context.getScalarAlgo() == SA_ZPROFILE ) {
         *        EASValsSetColor( context.getDeformedElementColor() );
         *        EASValsSetLineWidth(OOFEG_DEFORMED_GEOMETRY_WIDTH);
         *        tr =  CreateQuad3D(p);
         *        EGWithMaskChangeAttributes(WIDTH_MASK | COLOR_MASK | LAYER_MASK, tr);
         *    } else {
         *        context.updateFringeTableMinMax(s, 4);
         *        tr =  CreateQuadWD3D(p, s [ 0 ], s [ 1 ], s [ 2 ], s [ 3 ]);
         *        EGWithMaskChangeAttributes(LAYER_MASK, tr);
         *    }
         *
         *    EMAddGraphicsToModel(ESIModel(), tr);
         * }
         */
    } else if ( context.giveIntVarMode() == ISM_local ) {
        // ========== plot the local values (raw data) =====================
        if ( numberOfGaussPoints != 4 ) {
            return;
        }

        int ip;
        GaussPoint *gp;
        IntArray ind(4);
        FloatArray *gpCoords;
        WCRec pp [ 9 ];

        for ( i = 0; i < 8; i++ ) {
            if ( context.getInternalVarsDefGeoFlag() ) {
                // use deformed geometry
                defScale = context.getDefScale();
                pp [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(1, tStep, defScale);
                pp [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveUpdatedCoordinate(2, tStep, defScale);
                pp [ i ].z = 0.;
            } else {
                pp [ i ].x = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(1);
                pp [ i ].y = ( FPNum ) this->giveNode(i + 1)->giveCoordinate(2);
                pp [ i ].z = 0.;
            }
        }

        pp [ 8 ].x = 0.25 * ( pp [ 0 ].x + pp [ 1 ].x + pp [ 2 ].x + pp [ 3 ].x );
        pp [ 8 ].y = 0.25 * ( pp [ 0 ].y + pp [ 1 ].y + pp [ 2 ].y + pp [ 3 ].y );
        pp [ 8 ].z = 0.;

        for ( ip = 1; ip <= integrationRulesArray [ 0 ]->giveNumberOfIntegrationPoints(); ip++ ) {
            gp = integrationRulesArray [ 0 ]->getIntegrationPoint(ip - 1);
            gpCoords = gp->giveCoordinates();
            if ( ( gpCoords->at(1) > 0. ) && ( gpCoords->at(2) > 0. ) ) {
                ind.at(1) = 0;
                ind.at(2) = 4;
                ind.at(3) = 8;
                ind.at(4) = 7;
            } else if ( ( gpCoords->at(1) < 0. ) && ( gpCoords->at(2) > 0. ) ) {
                ind.at(1) = 4;
                ind.at(2) = 1;
                ind.at(3) = 5;
                ind.at(4) = 8;
            } else if ( ( gpCoords->at(1) < 0. ) && ( gpCoords->at(2) < 0. ) ) {
                ind.at(1) = 5;
                ind.at(2) = 2;
                ind.at(3) = 6;
                ind.at(4) = 8;
            } else {
                ind.at(1) = 6;
                ind.at(2) = 3;
                ind.at(3) = 7;
                ind.at(4) = 8;
            }

            if ( giveIPValue(v [ 0 ], gp, context.giveIntVarType(), tStep) == 0 ) {
                return;
            }

            indx = context.giveIntVarIndx();

            for ( i = 1; i <= 4; i++ ) {
                s [ i - 1 ] = v [ 0 ].at(indx);
            }

            for ( i = 0; i < 4; i++ ) {
                p [ i ].x = pp [ ind.at(i + 1) ].x;
                p [ i ].y = pp [ ind.at(i + 1) ].y;
                p [ i ].z = pp [ ind.at(i + 1) ].z;
            }

            context.updateFringeTableMinMax(s, 4);
            tr =  CreateQuadWD3D(p, s [ 0 ], s [ 1 ], s [ 2 ], s [ 3 ]);
            EGWithMaskChangeAttributes(LAYER_MASK, tr);
            EMAddGraphicsToModel(ESIModel(), tr);
        }
    }
}
Exemple #28
0
void genotype::read_vcf (string genofile, bool isgenoytpe) { 
    igzstream ig (genofile.c_str());
    string line;
	vector<snp> tmp;
	int j = 0 ;
	maxgpos = unordered_map<string, double> ();
	mingpos = unordered_map<string, double>();
	maxppos = unordered_map<string, double> ();
	minppos = unordered_map<string, double>();
	chrs = vector<string> ();
	double prevgpos ;
	double prevppos;
	string prevchr="";
    int size =  10000;
    int inc = 10000;
	
    int linenum = 0 ;
    bool setind = false;
    int numhap = 2;
    if (isgenotype)
        numhap = 1;
    while (std::getline (ig, line) ) {
        linenum ++;
        char c = line[0];
        if (c=='#') { 
            if (line.find ("CHROM")!=string::npos) {
                if (!givenind)  {
                    vector<string> toks;
                    functions::tokenize (line.c_str(), toks, " \t");
                    nind = toks.size() - 9 ;
                    nind *= numhap;
                    for (int i = 9 ; i < toks.size(); i++){
                        string id = toks[i];
                        indiv.push_back (ind(id,'U',"G"));
                        if (!isgenotype)
                            indiv.push_back (ind(id,'U',"G"));

                    }
                    setind = true;
                }
            }
        } else { 
            vector<string> toks;
            functions::tokenize (line.c_str(), toks, " \t");
            string id = toks[2];
            string chr = toks[0];
            double physpos =  atof(toks[1].c_str());
            double genpos = physpos*1.3/1e8;
            if (id.compare (".")==0) { 
                id = chr+":"+toks[1];
            }
            string ref = toks[3];
            string var = toks[4];
            string pass = toks[6];
            string desc = toks[7];
            string format = toks[8];
            if (pass.compare("PASS")!=0)
                continue;
            if (ref.compare (".")==0)
                continue;
            if (desc.compare (".") == 0 ) {
                cout << "Warning: No INFO field found. Assuming site is a SNP " << endl;
            }
            vector<string> tok1;
            functions::tokenize (desc.c_str(), tok1, ";");
            if (tok1[0].compare("SNP")!=0)
                continue;


            // Fill the snps
            if (chr.compare(prevchr)==0) {
                if (physpos >= prevppos){
                    prevgpos = genpos;
                    prevppos = physpos;
                } else {
                    cerr << "Invalid snps in  " << genofile <<" : Line " << linenum  << "\t Must have non-decreasing physical positions" << endl;
            //				exit (1);
                }
            } else {
                prevchr = chr;
                prevgpos = genpos;
                prevppos = physpos;
                if (snps.find(chr) != snps.end ()) {
                    cerr << "Invalid snps in "<< genofile << " : Line " << linenum << "\t SNPs on a chromosome must be consecutive" << endl;
                    exit (1);
                }
                chrs.push_back(chr);
                snps[chr] = vector<snp>();
//                snps[chr].reserve (size);
            }

/*            if (j==size){ 
                size += inc;
                snps[chr].reserve(size);
            }
            */

            if ( maxppos.find(chr) == maxppos.end()) {
                maxppos[chr] = physpos;
            } else if (physpos > maxppos[chr])
                maxppos[chr] = physpos;


            if ( minppos.find(chr) == minppos.end()) {
                minppos[chr] = physpos;
            } else if (physpos < minppos[chr])
                minppos[chr] = physpos;


            if ( maxgpos.find(chr) == maxgpos.end()) {
                maxgpos[chr] = genpos;
            } else if (genpos > maxgpos[chr])
                maxgpos[chr] = genpos;


            if ( mingpos.find(chr) == mingpos.end()) {
                mingpos[chr] = genpos;
            } else if (genpos < mingpos[chr])
                mingpos[chr] = genpos;

            // Fill in the genotypes
            tok1.resize (0);
            functions::tokenize (format.c_str(), tok1,":");
            int gind = -1;

            for (int i = 0 ; i < tok1.size(); i++){
                if (tok1[i].compare ("GT")==0) { 
                    gind = i;
                    break;
                }
            }
            if (gind == -1)
                continue;

            snps[chr].push_back (snp(id,chr,physpos,genpos,var,ref));
            vector<int> &gtype = snps[chr].back().gtype;
            j++;

            if (setind) {
                if (nind != numhap*(toks.size()-9)){
					cerr << "Bad genotype in " << genofile << ": Line "<< linenum  << endl;
					exit(1);
				}
            } else {
                nind = toks.size() - 9;
                nind *= numhap;
                setind = true;
            }

            gtype.resize(nind, 9);
            
            for (int i = 9, k = 0; i < toks.size(); i++, k++){ 
                tok1.resize(0);
                functions::tokenize(toks[i], tok1,",");
                if (isgenotype)  {
                    int a1 =  tok1[gind][0];
                    int a2 =  tok1[gind][2];
                    gtype[k] = (a1-48) + (a2-48);
                } else { 
                    int a1 =  tok1[gind][0];
                    int a2 =  tok1[gind][2];
                    gtype[2*k] = a1-48;
                    gtype[2*k+1] = a2-48;
                }
            }
            
        }
        if (j%10000==0) {
            io::println ("Read " + tostring (j) + " lines" ,0);
        }
    }
    nchr = chrs.size ();
    nsnps = j;
    
    if (io::debug >= 2 ) {
        cout << "genotype = " << to_string ();
    }

    ig.close ();

}
TEST_F(avl_tree, real_data_cycle)
{
	static const unsigned perf_mod=200000;

	recreate_dirs();
	ObjectProgress::log_generator lg(true);
	ObjectProgress::perfomance perf;

	static const size_t key_len=39;

	std::string file_name=std::string(src_dir)+"/13";
	regular_file_t fi(file_name+".idx");
	regular_file_t fd(file_name+".data");

	data_t idx_content(static_cast<size_t>(fi.get_size()));
	fi.load(0,idx_content);

	data_t data_content(static_cast<size_t>(fd.get_size()));
	fd.load(0,data_content);

	data_t key(key_len);
	data_t val,val_cp;
	steps_t steps;

	size_t mi=idx_content.size()/key_len;

	for(size_t i=0;i<mi;i++)
	{
		std::copy(idx_content.begin()+i*key_len,idx_content.begin()+(i+1)*key_len,key.begin());
		bin2points(key,steps);
		sort_steps(steps);
		points2bin(steps,key);

		std::copy(key.begin(),key.end(),idx_content.begin()+i*key_len);
	}

	{
		bin_index_t ind(index_dir,key_len);

		perf.reset();
		size_t data_pos=0;

		for(size_t i=0;i<mi;i++)
		{
			std::copy(idx_content.begin()+i*key_len,idx_content.begin()+(i+1)*key_len,key.begin());

			val.resize(*reinterpret_cast<const size_t*>(&data_content[data_pos] ));
			data_pos+=sizeof(size_t);
			std::copy(data_content.begin()+data_pos,data_content.begin()+data_pos+val.size(),val.begin());
			data_pos+=val.size();

			ind.set(key,val);

			if((i!=0)&&(i%perf_mod)==0)
			{
				ObjectProgress::perfomance::val_t v=perf.delay();
				lg<<"write: i="<<i<<" perf="<<(v/1000.0)<<"ms rate="<<(1.0*perf_mod/v*1000000.0)<<"rps";
				perf.reset();
			}
		}
	}

	{
		bin_index_t ind(index_dir,key_len);

		perf.reset();
		size_t data_pos=0;

		for(size_t i=0;i<mi;i++)
		{
			std::copy(idx_content.begin()+i*key_len,idx_content.begin()+(i+1)*key_len,key.begin());

			val.resize(*reinterpret_cast<const size_t*>(&data_content[data_pos] ));
			data_pos+=sizeof(size_t);
			std::copy(data_content.begin()+data_pos,data_content.begin()+data_pos+val.size(),val.begin());
			data_pos+=val.size();

			ASSERT_TRUE(ind.get(key,val_cp));

			ASSERT_EQ(val,val_cp);

			if((i!=0)&&(i%perf_mod)==0)
			{
				ObjectProgress::perfomance::val_t v=perf.delay();
				lg<<"read: i="<<i<<" perf="<<(v/1000.0)<<"ms rate="<<(1.0*perf_mod/v*1000000.0)<<"rps";
				perf.reset();
			}
		}
	}

	{
		size_t data_pos=0;
		std::map<data_t,data_t> idx;

		for(size_t i=0;i<mi;i++)
		{
			std::copy(idx_content.begin()+i*key_len,idx_content.begin()+(i+1)*key_len,key.begin());

			val.resize(*reinterpret_cast<const size_t*>(&data_content[data_pos] ));
			data_pos+=sizeof(size_t);
			std::copy(data_content.begin()+data_pos,data_content.begin()+data_pos+val.size(),val.begin());
			data_pos+=val.size();

			idx[key]=val;
		}

		bin_index_t ind(index_dir,key_len);

		perf.reset();
		
		size_t i=0;
		for(bool b=ind.first(key,val);b;b=ind.next(key,val),i++)
		{
			std::map<data_t,data_t>::iterator it=idx.find(key);
			
			ASSERT_TRUE(it!=idx.end());
			ASSERT_EQ(it->second,val);
			idx.erase(it);

			if((i!=0)&&(i%perf_mod)==0)
			{
				ObjectProgress::perfomance::val_t v=perf.delay();
				lg<<"next: i="<<i<<" perf="<<(v/1000.0)<<"ms rate="<<(1.0*perf_mod/v*1000000.0)<<"rps";
				perf.reset();
			}
		}

		ASSERT_EQ(idx.size(),0);
	}
}
Exemple #30
0
//Epsilon of Hy
static inline double EPSHY(const int i, const int j)
{
  return EPS_HY[ind(i,j)];
}