Пример #1
0
X(plan) X(plan_many_dft)(int rank, const int *n,
			 int howmany,
			 C *in, const int *inembed,
			 int istride, int idist,
			 C *out, const int *onembed,
			 int ostride, int odist, int sign, unsigned flags)
{
     R *ri, *ii, *ro, *io;

     if (!X(many_kosherp)(rank, n, howmany)) return 0;

     X(extract_reim)(sign, in, &ri, &ii);
     X(extract_reim)(sign, out, &ro, &io);

     return 
	  X(mkapiplan)(sign, flags,
		       X(mkproblem_dft_d)(
			    X(mktensor_rowmajor)(rank, n, 
						 N0(inembed), N0(onembed),
						 2 * istride, 2 * ostride),
			    X(mktensor_1d)(howmany, 2 * idist, 2 * odist),
			    TAINT_UNALIGNED(ri, flags),
			    TAINT_UNALIGNED(ii, flags),
			    TAINT_UNALIGNED(ro, flags),
			    TAINT_UNALIGNED(io, flags)));
}
Пример #2
0
 BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const
 {
   // Copy data in output first
   x_type  x = boost::proto::child_c<0>(a0);
   y_type  y = boost::proto::child_c<1>(a0);
   size_t l = lval(a0, N0());
   polcoefs(a1, x, y, l, N1());
 }
pointField quadrilateralDistribution::evaluate()
{
    // Read needed material
    label N0( readLabel(pointDict_.lookup("N0")) );
    label N1( readLabel(pointDict_.lookup("N1")) );

    point xs0( pointDict_.lookup("linestart0") );
    point xe0( pointDict_.lookup("lineend0") );
    point xe1( pointDict_.lookup("lineend1") );

    scalar stretch0( pointDict_.lookupOrDefault<scalar>("stretch0", 1.0) );
    scalar stretch1( pointDict_.lookupOrDefault<scalar>("stretch1", 1.0) );

    // Define the return field
    pointField res(N0*N1, xs0);

    // Compute the scaling factor
    scalar factor0(0.0);
    scalar factor1(0.0);

    for (int i=1; i < N0; i++)
    {
        factor0 += Foam::pow( stretch0, static_cast<scalar>(i) );
    }

    for (int i=1; i < N1; i++)
    {
        factor1 += Foam::pow( stretch1, static_cast<scalar>(i) );
    }

    point dx0( (xe0 - xs0)/factor0 );
    point dx1( (xe1 - xs0)/factor1 );

    // Compute points
    for (int j=0; j < N1; j++)
    {
        if (j != 0)
        {
            res[j*N0] = res[(j - 1)*N0]
                + Foam::pow( stretch1, static_cast<scalar>(j))*dx1;
        }

        for (int i=1; i < N0; i++)
        {
            res[i + j*N0] = res[i - 1 + j*N0]
                + Foam::pow( stretch0, static_cast<scalar>(i) )*dx0;
        }
    }

    return res;
}
Пример #4
0
bool ON_Mesh::CollapseEdge( int topei )
{
  ON_Mesh& mesh = *this;

  ON__MESHEDGE me;
  memset(&me,0,sizeof(me));
  const ON_MeshTopology& top = mesh.Topology();  
  const int F_count = mesh.m_F.Count();
  const int V_count = mesh.m_V.Count();
  const int topv_count = top.m_topv.Count();
  //const int tope_count = top.m_tope.Count();

  if ( topei < 0 || topei >= top.m_tope.Count() )
  {
    return false;
  }

  const ON_MeshTopologyEdge& tope = top.m_tope[topei];

  if (    tope.m_topf_count < 1 
       || tope.m_topvi[0] == tope.m_topvi[1] 
       || tope.m_topvi[0] < 0
       || tope.m_topvi[1] < 0
       || tope.m_topvi[0] >= topv_count
       || tope.m_topvi[1] >= topv_count )
  {
    return false;
  }

  const ON_MeshTopologyVertex& topv0 = top.m_topv[tope.m_topvi[0]];
  const ON_MeshTopologyVertex& topv1 = top.m_topv[tope.m_topvi[1]];
  if ( topv0.m_v_count < 1 || topv1.m_v_count < 1 )
  {
    return false;
  }
  if ( topv0.m_vi[0] < 0 || topv0.m_vi[0] >= V_count )
  {
    return false;
  }
  if ( topv1.m_vi[0] < 0 || topv1.m_vi[0] >= V_count )
  {
    return false;
  }
  
  // create a ON__MESHEDGE for each face (usually one or two) that uses the edge
  ON__MESHEDGE* me_list = (ON__MESHEDGE*)alloca(tope.m_topf_count*sizeof(me_list[0]));
  int me_list_count = 0;
  int efi;
  for ( efi = 0; efi < tope.m_topf_count; efi++ )
  {
    int fi = tope.m_topfi[efi];
    if ( fi < 0 || fi >= F_count )
      continue;
    const ON_MeshFace& f = mesh.m_F[fi];
    if ( !f.IsValid(V_count) )
      continue;
    me.vi1 = f.vi[3];
    me.topvi1 = top.m_topv_map[me.vi1];
    int fvi;
    for ( fvi = 0; fvi < 4; fvi++ )
    {
      me.vi0 = me.vi1;
      me.topvi0 = me.topvi1;
      me.vi1 = f.vi[fvi];
      me.topvi1 = top.m_topv_map[me.vi1];
      if ( me.vi0 != me.vi1 )
      {
        if (    (me.topvi0 == tope.m_topvi[0] && me.topvi1 == tope.m_topvi[1])
             || (me.topvi0 == tope.m_topvi[1] && me.topvi1 == tope.m_topvi[0]) )
        {
          if ( me.vi0 > me.vi1 )
          {
            int i = me.vi0; me.vi0 = me.vi1; me.vi1 = i;
            i = me.topvi0; me.topvi0 = me.topvi1; me.topvi1 = i;
          }
          me_list[me_list_count++] = me;
          break;
        }
      }
    }
  }

  if (me_list_count<1)
  {
    return false;
  }

  // Sort me_list[] so edges using same vertices are adjacent
  // to each other in the list.  This is needed so that non-manifold
  // crease edges will be properly collapsed.
  ON_qsort(me_list,me_list_count,sizeof(me_list[0]),(QSORTCMPFUNC)CompareMESHEDGE);

  // create new vertex or vertices that edge will be
  // collapsed to.
  mesh.m_C.Destroy();
  mesh.m_K.Destroy();
  
  int mei;
  bool bHasVertexNormals = mesh.HasVertexNormals();
  bool bHasTextureCoordinates = mesh.HasTextureCoordinates();
  bool bHasFaceNormals = mesh.HasFaceNormals();
  if ( topv0.m_v_count == 1 || topv1.m_v_count == 1 )
  {
    // a single new vertex
    ON_Line Vline(ON_origin,ON_origin);
    ON_Line Tline(ON_origin,ON_origin);
    ON_3dVector N0(0,0,0);
    ON_3dVector N1(0,0,0);
    ON_3dPoint P;
    int vi, tvi, cnt;

    int newvi = topv0.m_vi[0];

    cnt = 0;
    for ( tvi = 0; tvi < topv0.m_v_count; tvi++ )
    {
      vi = topv0.m_vi[tvi];
      if ( vi < 0 || vi > V_count )
        continue;
      if ( vi < newvi )
        newvi = vi;
      cnt++;
      P = mesh.m_V[vi];
      Vline.from += P;
      if ( bHasVertexNormals )
      {
        N0 += ON_3dVector(mesh.m_N[vi]);
      }
      if ( bHasTextureCoordinates )
      {
        P = mesh.m_T[vi];
        Tline.from += P;
      }
    }

    if (cnt > 1)
    {
      double s = 1.0/((double)cnt);
      Vline.from.x *= s;
      Vline.from.y *= s;
      Vline.from.z *= s;
      Tline.from.x *= s;
      Tline.from.y *= s;
      Tline.from.z *= s;
      N0 = s*N0;
    }

    cnt = 0;
    for ( tvi = 0; tvi < topv1.m_v_count; tvi++ )
    {
      vi = topv1.m_vi[tvi];
      if ( vi < 0 || vi > V_count )
        continue;
      if ( vi < newvi )
        newvi = vi;
      cnt++;
      P = mesh.m_V[vi];
      Vline.to += P;
      if ( bHasVertexNormals )
      {
        N1 += ON_3dVector(mesh.m_N[vi]);
      }
      if ( bHasTextureCoordinates )
      {
        P = mesh.m_T[vi];
        Tline.to += P;
      }
    }

    if (cnt > 1)
    {
      double s = 1.0/((double)cnt);
      Vline.to.x *= s;
      Vline.to.y *= s;
      Vline.to.z *= s;
      Tline.to.x *= s;
      Tline.to.y *= s;
      Tline.to.z *= s;
      N1 = s*N1;
    }

    ON_3fPoint newV(Vline.PointAt(0.5));
    ON_3fVector newN;
    ON_2fPoint newT;
    if ( bHasVertexNormals )
    {
      N0.Unitize();
      N1.Unitize();
      ON_3dVector N = N0+N1;
      if ( !N.Unitize() )
      {
        N = (topv0.m_v_count == 1) ? mesh.m_N[topv0.m_vi[0]] :mesh.m_N[topv1.m_vi[0]];
      }
      newN = N;
    }
    if ( bHasTextureCoordinates )
    {
      newT = Tline.PointAt(0.5);
    }
    for ( mei = 0; mei < me_list_count; mei++ )
    {
      me_list[mei].newvi = newvi;
      me_list[mei].newV = newV;
      me_list[mei].newN = newN;
      me_list[mei].newT = newT;
    }
  }
  else
  {
    // collapsing a "crease" edge - attempt to preserve
    // the crease.
    memset(&me,0,sizeof(me));
    me.vi0 = -1;
    me.vi1 = -1;
    for ( mei = 0; mei < me_list_count; mei++ )
    {
      if ( 0 == mei && CompareMESHEDGE(&me,me_list+mei) )
      {
        // cook up new vertex
        me_list[mei].newvi = mesh.m_V.Count();
        me = me_list[mei];
        ON_Line line;
        line.from = mesh.m_V[me.vi0];
        line.to   = mesh.m_V[me.vi1];
        me.newV = line.PointAt(0.5);
        if ( bHasVertexNormals )
        {
          ON_3dVector N0(mesh.m_N[me.vi0]);
          ON_3dVector N1(mesh.m_N[me.vi1]);
          ON_3dVector N = N0 + N1;
          if ( !N.Unitize() )
            N = N0;
          me.newN = N;
        }
        if ( bHasTextureCoordinates )
        {
          line.from = mesh.m_T[me.vi0];
          line.to   = mesh.m_T[me.vi1];
          me.newT = line.PointAt(0.5);
        }
        me.newvi = (me.vi0 < me.vi1) ? me.vi0 : me.vi1;
      }
      else
      {
        me_list[mei].newvi = me.newvi;
        me_list[mei].newV = me.newV;
        me_list[mei].newN = me.newN;
        me_list[mei].newT = me.newT;
      }
    }
  }

  // We are done averaging old mesh values.
  // Change values in mesh m_V[], m_N[] and m_T[] arrays.
  for ( mei = 0; mei < me_list_count; mei++ )
  {
    mesh.m_V[me_list[mei].vi0] = me_list[mei].newV;
    mesh.m_V[me_list[mei].vi1] = me_list[mei].newV;
    if ( bHasVertexNormals )
    {
      mesh.m_N[me_list[mei].vi0] = me_list[mei].newN;
      mesh.m_N[me_list[mei].vi1] = me_list[mei].newN;
    }
    if ( bHasTextureCoordinates )
    {
      mesh.m_T[me_list[mei].vi0] = me_list[mei].newT;
      mesh.m_T[me_list[mei].vi1] = me_list[mei].newT;
    }
  }

  // make a map of old to new
  int old2new_map_count = 0;
  ON__NEWVI* old2new_map = (ON__NEWVI*)alloca(2*me_list_count*sizeof(old2new_map[0]));

  for ( mei = 0; mei < me_list_count; mei++ )
  {
    old2new_map[old2new_map_count].oldvi = me_list[mei].vi0;
    old2new_map[old2new_map_count].newvi = me_list[mei].newvi;
    old2new_map_count++;
    old2new_map[old2new_map_count].oldvi = me_list[mei].vi1;
    old2new_map[old2new_map_count].newvi = me_list[mei].newvi;
    old2new_map_count++;
  }

  // sort old2new_map[] so we can use a fast bsearch() call
  // to update faces.
  ON_qsort(old2new_map,old2new_map_count,sizeof(old2new_map[0]),(QSORTCMPFUNC)CompareNEWVI);

  // count faces that use the vertices that are being changed
  int bad_fi_count = 0;
  int topv_end, vei, fi, fvi23, fvi;
  ON__NEWVI nvi;

  for ( topv_end = 0; topv_end < 2; topv_end++ )
  {
    const ON_MeshTopologyVertex& topv = (topv_end) ? topv1 : topv0;
    for ( vei = 0; vei < topv.m_tope_count; vei++ )
    {
      topei = topv.m_topei[vei];
      if ( topei < 0 && topei >= top.m_tope.Count() )
        continue;
      bad_fi_count += top.m_tope[topei].m_topf_count;
    }
  }
  int* bad_fi = (int*)alloca(bad_fi_count*sizeof(*bad_fi));
  bad_fi_count = 0;

  // Go through all the faces that use the vertices at the
  // ends of the edge and update the vi[] values to use the
  // new vertices.
  for ( topv_end = 0; topv_end < 2; topv_end++ )
  {
    const ON_MeshTopologyVertex& topv = (topv_end) ? topv1 : topv0;
    for ( vei = 0; vei < topv.m_tope_count; vei++ )
    {
      topei = topv.m_topei[vei];
      if ( topei < 0 && topei >= top.m_tope.Count() )
        continue;
      const ON_MeshTopologyEdge& e = top.m_tope[topei];
      for ( efi = 0; efi < e.m_topf_count; efi++ )
      {
        fi = e.m_topfi[efi];
        if ( fi < 0 || fi >= F_count )
          continue;
        bool bChangedFace = false;
        ON_MeshFace& f = mesh.m_F[fi];
        for ( fvi = 0; fvi < 4; fvi++ )
        {
          nvi.oldvi = f.vi[fvi];
          ON__NEWVI* p = (ON__NEWVI*)bsearch(&nvi,old2new_map,old2new_map_count,sizeof(old2new_map[0]),(QSORTCMPFUNC)CompareNEWVI);
          if ( 0 != p && p->oldvi != p->newvi)
          {
            f.vi[fvi] = p->newvi;
            bChangedFace = true;
          }
        }
        if ( bChangedFace )
        {
          if ( !f.IsValid(V_count) )
          {
            if ( f.vi[3] == f.vi[0] )
            {
              f.vi[0] = f.vi[1];
              f.vi[1] = f.vi[2];
              f.vi[2] = f.vi[3];
            }
            else if ( f.vi[0] == f.vi[1] )
            {
              fvi23 = f.vi[0];
              f.vi[0] = f.vi[2];
              f.vi[1] = f.vi[3];
              f.vi[2] = fvi23;
              f.vi[3] = fvi23;
            }
            else if ( f.vi[1] == f.vi[2] )
            {
              fvi23 = f.vi[1];
              f.vi[1] = f.vi[0];
              f.vi[0] = f.vi[3];
              f.vi[2] = fvi23;
              f.vi[3] = fvi23;
            }
            if ( f.vi[0] == f.vi[1] || f.vi[1] == f.vi[2] || f.vi[2] == f.vi[0] || f.vi[2] != f.vi[3] )
            {
              bad_fi[bad_fi_count++] = fi;
            }
          }
          if ( bHasFaceNormals )
          {
            // invalid faces are removed below
            ON_3fVector a, b, n;
            a = mesh.m_V[f.vi[2]] - mesh.m_V[f.vi[0]];
            b = mesh.m_V[f.vi[3]] - mesh.m_V[f.vi[1]];
            n = ON_CrossProduct( a, b );
            n.Unitize();
            mesh.m_FN[fi] = n;
          }
        }
      }
    }
  }

  if ( bad_fi_count > 0 )
  {
    // remove collapsed faces
    ON_qsort(bad_fi,bad_fi_count,sizeof(bad_fi[0]),CompareInt);
    int bfi = 1;
    int dest_fi = bad_fi[0];
    for ( fi = dest_fi+1; fi < F_count && bfi < bad_fi_count; fi++ )
    {
      if ( fi == bad_fi[bfi] )
      {
        bfi++;
      }
      else
      {
        mesh.m_F[dest_fi++] = mesh.m_F[fi];
      }
    }
    while (fi<F_count)
    {
      mesh.m_F[dest_fi++] = mesh.m_F[fi++];
    }
    mesh.m_F.SetCount(dest_fi);

    if ( bHasFaceNormals )
    {
      bfi = 1;
      dest_fi = bad_fi[0];
      for ( fi = dest_fi+1; fi < F_count && bfi < bad_fi_count; fi++ )
      {
        if ( fi == bad_fi[bfi] )
        {
          bfi++;
        }
        else
        {
          mesh.m_FN[dest_fi++] = mesh.m_FN[fi];
        }
      }
      while (fi<F_count)
      {
        mesh.m_FN[dest_fi++] = mesh.m_FN[fi++];
      }
      mesh.m_FN.SetCount(dest_fi);
    }
  }

  mesh.Compact();
  mesh.DestroyTopology();
  mesh.DestroyPartition();

  return true;
}
Пример #5
0
int main(int argc, char *argv[])
{
	int i,j,k;			//Counter variable
	
	bvec b_source_bits, b_decoded_bits, b_encoded_bits;
	ivec i_decoded_bits, i_decoded_symbols;
	cvec c_received_signals;
	vec  d_received_llr;
	ivec No_of_Errors, No_of_Bits, No_of_BlockErrors, No_of_Blocks;
	
	//Channel setup
	cvec channel_gains;
	TDL_Channel ray_channel; // default: uncorrelated Rayleigh fading channel
        AWGN_Channel awgn_channel; // AWGN channel
	
	//-------------------------------------------------------CONV
	//Convolutional codes module, CONV
	CONV conv;
	char *ctrlfile;
	if(argc==1) ctrlfile = "control.conv.par";
	else        ctrlfile = argv[1];
	
	conv.set_parameters_from_file(ctrlfile);
	conv.initialise();
	
	//result file
	FILE *f;  char *resultfile= conv.get_result_filename();
	f=fopen(resultfile, "w");
	
	//print out parameters
	conv.print_parameters(stdout);    
	conv.print_parameters(f);
	//-------------------------------------------------------CONV	
	
	// read simulation parameters
	FILE *sim_file;
	FILESERVICE fileser;
	sim_file = fopen("control.sim.par", "r");
	if(sim_file==NULL) it_error("control.sim.par not found");
	int max_nrof_frame = fileser.scan_integer(sim_file);
	double SNR_start  = fileser.scan_double(sim_file); 
	double SNR_step   = fileser.scan_double(sim_file);
	double SNR_end    = fileser.scan_double(sim_file);
	double G_sd        = fileser.scan_double(sim_file);
	double G_sr        = fileser.scan_double(sim_file);
	double G_rd        = fileser.scan_double(sim_file);
	int channel_type   = fileser.scan_integer(sim_file);
	int mapper_bps     = fileser.scan_integer(sim_file);
	fclose(sim_file);
	char text[100];
	sprintf( text, "%f:%f:%f", SNR_start, SNR_step, SNR_end );
	
	//SNR setup
	vec SNRdB = text;	//Setting the simulation Eb/N0 range in dB


	int M = 1<<mapper_bps;
        PSK psk(M);
	cvec source_frame;
	
	double rate = (double)mapper_bps * conv.get_rate(); 

	printf (  "! %d-PSK (mapper_bps=%d) :: Overall_Rate=%.4f\n!\n", M, mapper_bps, rate);
	fprintf(f,"! %d-PSK (mapper_bps=%d) :: Overall_Rate=%.4f\n!\n", M, mapper_bps, rate);

	vec SNR    = pow(10.0, SNRdB/10.0);
	vec N0     = 1.0/SNR;
	vec sigma2 = N0/2;

	
	BERC berc;			//BER counter
	BLERC blerc;			//FER counter
	Real_Timer tt;			//Time counter

	vec ber(SNRdB.length());	//allocate memory for vector to store BER
	vec bler(SNRdB.length());	//allocate memory for vector to store FER
	
	ber.clear();			//Clear up buffer of BER counter
	bler.clear();			//Clear up buffer of FER counter	
	
	blerc.set_blocksize((long)conv.get_info_bit_length());	//set blocksize of the FER counter
	
	tt.tic();					//Start timer
	
	//RNG_randomize();				//construct random source 
	RNG_reset(0);                                   //reset random seed 
	
	b_source_bits.set_size(conv.get_info_bit_length(), false);
	b_encoded_bits.set_size(conv.get_coded_bit_length(), false);
	c_received_signals.set_size(conv.get_sym_length(), false);
	d_received_llr.set_size(conv.get_coded_bit_length(), false);
	b_decoded_bits.set_size(conv.get_info_bit_length(), false);
	
	No_of_Errors.set_size(SNRdB.length(), false);		//Set the length
	No_of_Bits.set_size(SNRdB.length(), false);		//for ivectors storing the no	
	No_of_BlockErrors.set_size(SNRdB.length(),false);	//of errors bits or error frames
	No_of_Blocks.set_size(SNRdB.length(),false);
			
	No_of_Errors.clear();
	No_of_Bits.clear();
	No_of_BlockErrors.clear();
	No_of_Blocks.clear();
	
	printf (  "!SNR(dB)\tEbN0(dB)\tBER\t\tFER\t\tnrof Frames\n");
	fprintf(f,"!SNR(dB)\tEbN0(dB)\tBER\t\tFER\t\tnrof Frames\n");
	
	for(i=0; i< SNRdB.length(); i++)
	{
		//Set channel noise level
		awgn_channel.set_noise(N0(i));
		
		for(j=0;j<max_nrof_frame;j++)
		{			
		        //Generate random source bits
			b_source_bits = randb(conv.get_info_bit_length());
			
			//CONV encode
			conv.encode_bits(b_source_bits, b_encoded_bits);
			
			source_frame = psk.modulate_bits(b_encoded_bits);
			
			// Fast Rayleigh channel + AWGN transmission 
			channel_gains = my_channel(channel_type, source_frame.length(), G_sd, ray_channel); 
			c_received_signals = elem_mult(source_frame, channel_gains);
			c_received_signals = awgn_channel( c_received_signals );
			
			//Demodulation to get llr
			psk.demodulate_soft_bits(c_received_signals, channel_gains, N0(i), d_received_llr);
			//Convert to Log(Pr=1/Pr=0)
                        d_received_llr = -1 * d_received_llr;

			//CONV decode
			conv.assign_apr_codeword(d_received_llr);
			conv.decode(i_decoded_bits, i_decoded_symbols);

			b_decoded_bits = to_bvec(i_decoded_bits.left(conv.get_info_bit_length())); 
			// remove dummy bits if trellis/code termination is used
			
			berc.clear();
			blerc.clear();
			
			berc.count (b_source_bits, b_decoded_bits);	//Count error bits in a word
			blerc.count (b_source_bits, b_decoded_bits);	//Count frame errors
			
			No_of_Errors(i) += berc.get_errors();		//Updating counters	
			No_of_Bits(i) += berc.get_errors()+berc.get_corrects();
			No_of_BlockErrors(i) +=blerc.get_errors();
			No_of_Blocks(i)++;
			
			if(No_of_Errors(i)>100000)
				break;
		}
		
		ber(i) = (double)No_of_Errors(i)/No_of_Bits(i);
		bler(i) = (double)No_of_BlockErrors(i)/No_of_Blocks(i);
		
		double EbN0dB = SNRdB(i) - 10*log10(rate);
		
		printf("%f\t%f\t%e\t%e\t%d\n",    SNRdB(i), EbN0dB, ber(i), bler(i), No_of_Blocks(i));
		fprintf(f,"%f\t%f\t%e\t%e\t%d\n", SNRdB(i), EbN0dB, ber(i), bler(i), No_of_Blocks(i));
		
		if(ber(i)<1e-5)  break;			
	}

	fprintf(f,"!Elapsed time = %d s\n", tt.get_time());		//output simulation time
	tt.toc();							//Stop timer and output simulation time
	
	fclose(f);							//close output file	
	return 0 ;							//exit program
}
Пример #6
0
void KFKSDS_deriv_C (int *dim, double *sy, double *sZ, double *sT, double *sH, 
  double *sR, double *sV, double *sQ, double *sa0, double *sP0, double *dvof, 
  double *epshat, double *vareps, double *etahat, double *vareta, 
  double *r, double *N, double *dr, double *dN, 
  double *dahat, double *dvareps)
{
  //int s, p = dim[1], mp1 = m + 1;
  int i, ip1, j, k, n = dim[0], m = dim[2], 
    ir = dim[3], rp1 = ir + 1, nrp1 = n * rp1,
    rp1m = rp1 * m, iaux, irp1m,
    irsod = ir * sizeof(double), msod = m * sizeof(double), 
    nsod = n * sizeof(double), rp1msod = rp1 * msod;

  //double invf[n], vof[n], msHsq, dfinvfsq[nrp1];
  double msHsq;
  std::vector<double> invf(n);
  std::vector<double> vof(n);
  std::vector<double> dfinvfsq(nrp1);

  gsl_matrix_view Q = gsl_matrix_view_array(sQ, m, m);
  
  gsl_vector_view Z = gsl_vector_view_array(sZ, m);  
  gsl_vector * Z_cp = gsl_vector_alloc(m);

  gsl_matrix * ZtZ = gsl_matrix_alloc(m, m);
  gsl_matrix_view maux1, maux2;
  maux1 = gsl_matrix_view_array(gsl_vector_ptr(&Z.vector, 0), m, 1);
  gsl_vector_memcpy(Z_cp, &Z.vector);
  maux2 = gsl_matrix_view_array(gsl_vector_ptr(Z_cp, 0), 1, m);
  gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &maux1.matrix, 
    &maux2.matrix, 0.0, ZtZ);
  
  gsl_matrix * a_pred = gsl_matrix_alloc(n, m);
  std::vector<gsl_matrix*> P_pred(n);
    
  gsl_matrix * K = gsl_matrix_alloc(n, m);
  gsl_vector_view K_irow;
  
  std::vector<gsl_matrix*> L(n);
  
  gsl_vector_view Qdiag = gsl_matrix_diagonal(&Q.matrix);
  gsl_vector * Qdiag_msq = gsl_vector_alloc(m);
  gsl_vector_memcpy(Qdiag_msq, &Qdiag.vector);
  gsl_vector_mul(Qdiag_msq, &Qdiag.vector);
  gsl_vector_scale(Qdiag_msq, -1.0);
  
  std::vector<gsl_matrix*> da_pred(rp1);

  std::vector< std::vector<gsl_matrix*> > dP_pred(n, std::vector<gsl_matrix*>(rp1));

  std::vector<gsl_matrix*> dK(n);
  
  // filtering
  
  KF_deriv_aux_C(dim, sy, sZ, sT, sH, sR, sV, sQ, sa0, sP0, 
    &invf, &vof, dvof, &dfinvfsq, a_pred, &P_pred, K, 
    &L, &da_pred, &dP_pred, &dK);

  // state vector smoothing and disturbances smoothing

  gsl_matrix_view V = gsl_matrix_view_array(sV, ir, ir);  
  gsl_matrix_view R = gsl_matrix_view_array(sR, m, ir);
  
  gsl_vector_view vaux;
  gsl_vector *vaux2 = gsl_vector_alloc(m);
  
  gsl_matrix *Mmm = gsl_matrix_alloc(m, m);
  gsl_matrix *Mmm2 = gsl_matrix_alloc(m, m);
  gsl_matrix *Mrm = gsl_matrix_alloc(ir, m);

  gsl_vector_memcpy(Z_cp, &Z.vector);
  
  gsl_matrix *r0 = gsl_matrix_alloc(n + 1, m);
  gsl_vector_view r_row_t;
  gsl_vector_view r_row_tp1 = gsl_matrix_row(r0, n);
  gsl_vector_set_zero(&r_row_tp1.vector);

  std::vector<gsl_matrix*> N0(n + 1);
  N0.at(n) = gsl_matrix_calloc(m, m);
  gsl_vector_view Ndiag;

  gsl_vector *var_eps = gsl_vector_alloc(n);  
  msHsq = -1.0 * pow(*sH, 2);
  //vaux = gsl_vector_view_array(invf, n);
  vaux = gsl_vector_view_array(&invf[0], n);
  gsl_vector_set_all(var_eps, msHsq);
  gsl_vector_mul(var_eps, &vaux.vector);
  gsl_vector_add_constant(var_eps, *sH);

  gsl_vector *vr = gsl_vector_alloc(ir);

  gsl_matrix *dL = gsl_matrix_alloc(m, m);

  std::vector<gsl_matrix*> dr0(n + 1);
  dr0.at(n) = gsl_matrix_calloc(rp1, m);
  gsl_vector_view dr_row_t, dr_row_tp1;

  std::vector< std::vector<gsl_matrix*> > dN0(n + 1, std::vector<gsl_matrix*>(rp1));
  
  for (j = 0; j < rp1; j++)
  {
    (dN0.at(n)).at(j) = gsl_matrix_calloc(m, m);
  }

  for (i = n-1; i > -1; i--)
  {
    ip1 = i + 1;
    iaux = (i-1) * rp1m;
    irp1m = i * rp1m;

    if (i != n-1)  //the case i=n-1 was initialized above
      r_row_tp1 = gsl_matrix_row(r0, ip1);
    r_row_t = gsl_matrix_row(r0, i);

    gsl_blas_dgemv(CblasTrans, 1.0, L.at(i), &r_row_tp1.vector, 
      0.0, &r_row_t.vector);
    gsl_vector_memcpy(Z_cp, &Z.vector);
    gsl_vector_scale(Z_cp, vof.at(i));
    gsl_vector_add(&r_row_t.vector, Z_cp);

    gsl_vector_memcpy(vaux2, &r_row_tp1.vector);
    memcpy(&r[i * m], vaux2->data, msod);
    
    N0.at(i) = gsl_matrix_alloc(m, m);
    gsl_matrix_memcpy(N0.at(i), ZtZ);
    gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, L.at(i), N0.at(ip1), 0.0, Mmm);
    gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Mmm, L.at(i), invf.at(i), N0.at(i));
    
    vaux = gsl_matrix_diagonal(N0.at(ip1));
    gsl_vector_memcpy(vaux2, &vaux.vector);
    memcpy(&N[i * m], vaux2->data, msod);

    K_irow = gsl_matrix_row(K, i);
    gsl_blas_ddot(&K_irow.vector, &r_row_tp1.vector, &epshat[i]);
    epshat[i] -= vof.at(i);
    epshat[i] *= -*sH;

    maux1 = gsl_matrix_view_array(gsl_vector_ptr(&K_irow.vector, 0), 1, m);
    maux2 = gsl_matrix_view_array(gsl_vector_ptr(Z_cp, 0), 1, m);    
    gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &maux1.matrix, N0.at(ip1),
      0.0, &maux2.matrix);
    vaux = gsl_vector_view_array(gsl_vector_ptr(var_eps, i), 1);
    gsl_blas_dgemv(CblasNoTrans, msHsq, &maux2.matrix, &K_irow.vector, 
      1.0, &vaux.vector);

    gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, &V.matrix, &R.matrix,
      0.0, Mrm);
    gsl_blas_dgemv(CblasNoTrans, 1.0, Mrm, &r_row_tp1.vector,
      0.0, vr);
    memcpy(&etahat[i*ir], vr->data, irsod);

    Ndiag = gsl_matrix_diagonal(N0.at(ip1));
    gsl_vector_memcpy(Z_cp, &Ndiag.vector); 
    gsl_vector_mul(Z_cp, Qdiag_msq);
    gsl_vector_add(Z_cp, &Qdiag.vector);
    gsl_blas_dgemv(CblasTrans, 1.0, &R.matrix, Z_cp, 0.0, vr);    
    memcpy(&vareta[i*ir], vr->data, irsod);

    // derivatives 

    dr0.at(i) = gsl_matrix_alloc(rp1, m);
    
    for (j = 0; j < rp1; j++)
    {
      k = i + j * n;
      
      gsl_vector_memcpy(Z_cp, &Z.vector);
      gsl_vector_scale(Z_cp, dvof[k]);      

      vaux = gsl_matrix_row(dK.at(i), j);
      maux1 = gsl_matrix_view_array(gsl_vector_ptr(&vaux.vector, 0), m, 1);
      maux2 = gsl_matrix_view_array(gsl_vector_ptr(&Z.vector, 0), 1, m);
      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &maux1.matrix, 
        &maux2.matrix, 0.0, dL);

      dr_row_t = gsl_matrix_row(dr0.at(i), j);
      dr_row_tp1 = gsl_matrix_row(dr0.at(ip1), j);
      gsl_blas_dgemv(CblasTrans, 1.0, dL, &r_row_tp1.vector, 0.0, &dr_row_t.vector);
      gsl_vector_add(&dr_row_t.vector, Z_cp);
      gsl_blas_dgemv(CblasTrans, 1.0, L.at(i), &dr_row_tp1.vector, 1.0, &dr_row_t.vector);

      (dN0.at(i)).at(j) = gsl_matrix_alloc(m, m);
      gsl_matrix_memcpy((dN0.at(i)).at(j), ZtZ);
      gsl_matrix_scale((dN0.at(i)).at(j), -1.0 * dfinvfsq.at(k));
      gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, dL, N0.at(ip1), 0.0, Mmm);
      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Mmm, L.at(i), 
        1.0, (dN0.at(i)).at(j));
      gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, L.at(i), 
        (dN0.at(ip1)).at(j), 0.0, Mmm);
      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Mmm, L.at(i), 
        1.0, (dN0.at(i)).at(j));
      gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, L.at(i), 
        N0.at(ip1), 0.0, Mmm);
      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Mmm, dL, 
        1.0, (dN0.at(i)).at(j));
      if (i != 0)
      {
        vaux = gsl_matrix_diagonal((dN0.at(i)).at(j));
        gsl_vector_memcpy(vaux2, &vaux.vector);
        memcpy(&dN[iaux + j * m], vaux2->data, msod);
      }

      vaux = gsl_matrix_row(da_pred.at(j), i);
      gsl_blas_dgemv(CblasNoTrans, 1.0, (dP_pred.at(i)).at(j) , &r_row_t.vector, 
        1.0, &vaux.vector);
      gsl_blas_dgemv(CblasNoTrans, 1.0, P_pred.at(i), &dr_row_t.vector, 
        1.0, &vaux.vector);
      gsl_vector_memcpy(vaux2, &vaux.vector);
      memcpy(&dahat[irp1m + j * m], vaux2->data, msod);

      gsl_matrix_memcpy(Mmm, (dP_pred.at(i)).at(j));
      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, (dP_pred.at(i)).at(j), 
        N0.at(i), 0.0, Mmm2);
      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Mmm2, P_pred.at(i),
        1.0, Mmm);
      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, P_pred.at(i), 
        (dN0.at(i)).at(j), 0.0, Mmm2);
      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Mmm2, P_pred.at(i),
        1.0, Mmm);
      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, P_pred.at(i), 
        N0.at(i), 0.0, Mmm2);
      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Mmm2,
        (dP_pred.at(i)).at(j), 1.0, Mmm);
      
      gsl_matrix_mul_elements(Mmm, ZtZ);
      std::vector<double> vmm(Mmm->data, Mmm->data + m*m);
      dvareps[i*rp1 + j] = std::accumulate(vmm.begin(), vmm.end(), 0.0);

      gsl_matrix_free((dN0.at(ip1)).at(j));    
      gsl_matrix_free((dP_pred.at(i)).at(j));

    }

    if (i != 0)
    {
      memcpy(&dr[iaux], (dr0.at(i))->data, rp1msod);
    }

    gsl_matrix_free(dr0.at(ip1));
    
    gsl_matrix_free(dK.at(i));
    gsl_matrix_free(P_pred.at(i));
    gsl_matrix_free(L.at(i));
    gsl_matrix_free(N0.at(ip1));
  }

  gsl_matrix_free(N0.at(0));
  gsl_matrix_free(dr0.at(0));
  for (j = 0; j < rp1; j++)
  {
    gsl_matrix_free((dN0.at(0)).at(j));
    gsl_matrix_free(da_pred.at(j));
  }
  
  memcpy(&vareps[0], var_eps->data, nsod);
  
  gsl_matrix_free(Mmm);
  gsl_matrix_free(Mmm2);
  gsl_matrix_free(Mrm);
  
  gsl_matrix_free(r0);
  gsl_matrix_free(K);
  gsl_matrix_free(dL);
  
  gsl_matrix_free(a_pred);
  
  gsl_vector_free(Z_cp);
  gsl_matrix_free(ZtZ);
  gsl_vector_free(var_eps);
  gsl_vector_free(vr);
  gsl_vector_free(Qdiag_msq);
  gsl_vector_free(vaux2);
}}
Пример #7
0
 BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const
 {
   bool    first =  true;
   getparams(a0, first, N0());
   compute(a0, a1, first, N1());
 }
Пример #8
0
bool ccDish::buildUp()
{
	if (m_drawPrecision < MIN_DRAWING_PRECISION)
		return false;

	if (m_height <= 0 || m_baseRadius <= 0 || m_secondRadius < 0) //invalid parameters
		return false;

	//section angular span
	double startAngle_rad = 0.0;
	const double endAngle_rad = M_PI/2.0;

	PointCoordinateType realRadius = m_baseRadius;
	if (m_secondRadius == 0 && m_height<m_baseRadius) //partial spherical mode
	{
		realRadius = (m_height*m_height+m_baseRadius*m_baseRadius)/(2*m_height);
		startAngle_rad = acos(m_baseRadius/realRadius);
		assert(startAngle_rad<endAngle_rad);
	}

	const unsigned steps = m_drawPrecision;
	double angleStep_rad = 2.0*M_PI/steps;
	unsigned sectionSteps = static_cast<unsigned>(ceil((endAngle_rad-startAngle_rad)*m_drawPrecision/(2.0*M_PI)));
	double sectionAngleStep_rad = (endAngle_rad-startAngle_rad)/sectionSteps;

	//vertices
	unsigned vertCount = steps*sectionSteps+1; //+1 for noth pole
	//faces
	unsigned faceCount = steps*((sectionSteps-1)*2+1);

	if (!init(vertCount,true,faceCount,0))
	{
		ccLog::Error("[ccDish::buildUp] Not enough memory");
		return false;
	}

	//vertices
	ccPointCloud* verts = vertices();
	assert(verts);

	//first point: north pole
	verts->addPoint(CCVector3(0,0,m_height));
	verts->addNorm(CCVector3(0,0,1));

	//then, angular sweep
	{
		for (unsigned j=1; j<=sectionSteps; ++j)
		{
			PointCoordinateType theta = static_cast<PointCoordinateType>(endAngle_rad - j * sectionAngleStep_rad); //we start from north pole!
			PointCoordinateType cos_theta = cos(theta);
			PointCoordinateType sin_theta = sin(theta);

			CCVector3 N0(cos_theta, 0, sin_theta);
		
			for (unsigned i=0; i<steps; ++i) //then we make a full revolution
			{
				PointCoordinateType phi = static_cast<PointCoordinateType>(i * angleStep_rad);
				PointCoordinateType cos_phi = cos(phi);
				PointCoordinateType sin_phi = sin(phi);

				CCVector3 N(N0.x * cos_phi, N0.x * sin_phi, N0.z);
				N.normalize();

				CCVector3 P = N * realRadius;

				if (m_secondRadius > 0) //half-ellipsoid mode
				{
					P.y *= (m_secondRadius / m_baseRadius);
					P.z *= (m_height / m_baseRadius);
				}
				else //spherical section mode
				{
					P.z += m_height-realRadius;
				}

				verts->addPoint(P);
				verts->addNorm(N);
			}
		}
	}

	//faces
	{
		//north pole
		{
			for (unsigned i=0; i<steps; ++i)
			{
				unsigned A = 1+i;
				unsigned B = (i+1<steps ? A+1 : 1);
				addTriangle(A,B,0);
			}
		}

		//slices
		for (unsigned j=1; j<sectionSteps; ++j)
		{
			unsigned shift = 1+(j-1)*steps;		
			for (unsigned i=0; i<steps; ++i)
			{
				unsigned A = shift+i;
				unsigned B = (i+1<steps ? A+1 : shift);
				assert(B < vertCount);
				addTriangle(A,A+steps,B);
				addTriangle(B+steps,B,A+steps);
			}
		}
	}

	notifyGeometryUpdate();
	showNormals(true);

	return true;
}
Пример #9
0
CORASMA_BER_Test::CORASMA_BER_Test()
{
    modem=new Modem_CORASMA();
    int L=1;
    int OF=1;

    cmat fading;
    cvec channel1,channel2,channel3,channel4,channel5,channel6,channel7,channel8,channel9,channel10,channel11,channel12,channel13,channel14,channel15,channel16;
    bvec transmitted_bits;
    bvec received_bits;
    cvec sum_chips;
    cvec transmitted_symbols;
    cvec received_chips;
    double norm_fading;
    BERC berc,berc1,berc2;
    AWGN_Channel channel;

    vec EbN0dB = linspace(1000, 1000, 1);
    vec EbN0 = pow(10, EbN0dB / 10);
    double Eb = 1.0;
    vec N0 = Eb * pow(EbN0, -1.0);
    int NumOfBits = modem->nb_bits;
    int MaxIterations = 10;
    int MaxNrOfErrors = 200;
    int MinNrOfErrors = 5;
    vec ber;
    ber.set_size(EbN0dB.size(), false);
    ber.clear();
    RNG_randomize();



    for (int i=0;i<EbN0dB.length();i++){

        cout << endl << "Simulating point nr " << i + 1 << endl;
        berc.clear();
        berc1.clear();
        berc2.clear();
        channel.set_noise(N0(i));

        for (int j=0;j<MaxIterations;j++) {

            transmitted_bits = randb(NumOfBits);
            sum_chips=modem->modulate(transmitted_bits);


            transmitted_symbols.set_length(sum_chips.length()+L+1);
            transmitted_symbols.zeros();

            fading.set_size(L,sum_chips.length());
            fading.zeros();

            channel1.set_length(sum_chips.length());
/*          channel2.set_length(sum_chips.length());
            channel3.set_length(sum_chips.length());
            channel4.set_length(sum_chips.length());
            channel5.set_length(sum_chips.length());
            channel6.set_length(sum_chips.length());
            channel7.set_length(sum_chips.length());
            channel8.set_length(sum_chips.length());
            channel9.set_length(sum_chips.length());
            channel10.set_length(sum_chips.length());
            channel11.set_length(sum_chips.length());
            channel12.set_length(sum_chips.length());
            channel13.set_length(sum_chips.length());
            channel14.set_length(sum_chips.length());
            channel15.set_length(sum_chips.length());
            channel16.set_length(sum_chips.length());*/


            for(int k=0;k<sum_chips.length()/OF;k++){


                channel1.replace_mid(k*OF,ones_c(OF));

/*              channel1.replace_mid(k*OF,randn_c()*ones(OF));
                channel2.replace_mid(k*OF,randn_c()*ones(OF));
                channel3.replace_mid(k*OF,randn_c()*ones(OF));
                channel4.replace_mid(k*OF,randn_c()*ones(OF));
                channel5.replace_mid(k*OF,randn_c()*ones(OF));
                channel6.replace_mid(k*OF,randn_c()*ones(OF));
                channel7.replace_mid(k*OF,randn_c()*ones(OF));
                channel8.replace_mid(k*OF,randn_c()*ones(OF));
                channel9.replace_mid(k*OF,randn_c()*ones(OF));
                channel10.replace_mid(k*OF,randn_c()*ones(OF));
                channel11.replace_mid(k*OF,randn_c()*ones(OF));
                channel12.replace_mid(k*OF,randn_c()*ones(OF));
                channel13.replace_mid(k*OF,randn_c()*ones(OF));
                channel14.replace_mid(k*OF,randn_c()*ones(OF));
                channel15.replace_mid(k*OF,randn_c()*ones(OF));
                channel16.replace_mid(k*OF,randn_c()*ones(OF));*/

            }


            norm_fading=1./sqrt(inv_dB(0)*norm(channel1)*norm(channel1)/sum_chips.length()/*+inv_dB(0)*norm(channel2)*norm(channel2)/sum_chips.length()+inv_dB(0)*norm(channel3)*norm(channel3)/sum_chips.length()+inv_dB(0)*norm(channel4)*norm(channel4)/sum_chips.length()+inv_dB(0)*norm(channel5)*norm(channel5)/sum_chips.length()+inv_dB(0)*norm(channel6)*norm(channel6)/sum_chips.length()+inv_dB(0)*norm(channel7)*norm(channel7)/sum_chips.length()+inv_dB(0)*norm(channel8)*norm(channel8)/sum_chips.length()+inv_dB(0)*norm(channel9)*norm(channel9)/sum_chips.length()+inv_dB(0)*norm(channel10)*norm(channel10)/sum_chips.length()+inv_dB(0)*norm(channel11)*norm(channel11)/sum_chips.length()+inv_dB(0)*norm(channel12)*norm(channel12)/sum_chips.length()+inv_dB(0)*norm(channel13)*norm(channel13)/sum_chips.length()+inv_dB(0)*norm(channel14)*norm(channel14)/sum_chips.length()+inv_dB(0)*norm(channel15)*norm(channel15)/sum_chips.length()+inv_dB(0)*norm(channel16)*norm(channel16)/sum_chips.length()*/);
            fading.set_row(0,norm_fading*channel1);
/*          fading.set_row(1,norm_fading*channel2);
            fading.set_row(2,norm_fading*channel3);
            fading.set_row(3,norm_fading*channel4);
            fading.set_row(4,norm_fading*channel5);
            fading.set_row(5,norm_fading*channel6);
            fading.set_row(6,norm_fading*channel7);
            fading.set_row(7,norm_fading*channel8);
            fading.set_row(8,norm_fading*channel9);
            fading.set_row(9,norm_fading*channel10);
            fading.set_row(10,norm_fading*channel11);
            fading.set_row(11,norm_fading*channel12);
            fading.set_row(12,norm_fading*channel13);
            fading.set_row(13,norm_fading*channel14);
            fading.set_row(14,norm_fading*channel15);
            fading.set_row(15,norm_fading*channel16);*/

            for (int k=0;k<L;k++){
                transmitted_symbols+=concat(zeros_c(k),elem_mult(to_cvec(sum_chips),fading.get_row(k)),zeros_c(L+1-k));
            }
            received_chips = channel(/*transmitted_symbols*/sum_chips);

            cvec constellation;
            int time_offset_estimate;
            received_bits=modem->demodulate(received_chips,constellation,time_offset_estimate);
            bvec received_bits_inverted=received_bits+bin(1);
            //Generic Transmitter + First Receiver M&M + Costas
            berc1.count(transmitted_bits, received_bits);
            ber(i) = berc1.get_errorrate();
            berc=berc1;
            berc2.count(transmitted_bits, received_bits_inverted);
            if(berc2.get_errorrate()<ber(i)){
                ber(i) = berc2.get_errorrate();
                berc=berc2;
            }
            cout << "   Iteration " << j + 1 << ": ber = " << berc.get_errorrate() << endl;
            if (berc.get_errors() > MaxNrOfErrors) {
                cout << "Breaking on point " << i + 1 << " with " << berc.get_errors() << " errors." << endl;
                break;
            }

        }

        if (berc.get_errors() < MinNrOfErrors) {
            cout << "Exiting Simulation on point " << i + 1 << endl;
            break;
        }

    }

    //Print results:
    cout << endl;
    cout << "EbN0dB = " << EbN0dB << endl;
    cout << "ber = " << ber << endl;

}
Пример #10
0
MCDAAOFDM_BER_Test::MCDAAOFDM_BER_Test()
{

    modem=new Modem_MCDAAOFDM();
    int L=1;
    int quasi_static=modem->Nfft+modem->Ncp;

    cmat fading;
    cvec channel1,channel2,channel3,channel4,channel5,channel6,channel7,channel8,channel9,channel10,channel11,channel12,channel13,channel14,channel15,channel16;
    bvec transmitted_bits;
    bvec received_bits;
    cvec modulated_ofdm;
    cvec transmitted_symbols;
    cvec received_ofdm;
    double norm_fading;
    BERC berc;
    AWGN_Channel channel;

    vec EbN0dB = linspace(0, 40, 41);
    vec EbN0 = pow(10, EbN0dB / 10);
    double Eb = 1.0;
    vec N0 = Eb * pow(EbN0, -1.0);
    int NumOfBits = 1000000;
    int MaxIterations = 10;
    int MaxNrOfErrors = 200;
    int MinNrOfErrors = 5;
    vec ber;
    ber.set_size(EbN0dB.size(), false);
    ber.clear();
    RNG_randomize();



    for (int i=0;i<EbN0dB.length();i++){

        cout << endl << "Simulating point nr " << i + 1 << endl;
        berc.clear();
        channel.set_noise(N0(i));

        for (int j=0;j<MaxIterations;j++) {

            transmitted_bits = randb(NumOfBits);
            modulated_ofdm=sqrt(modem->Nfft+modem->Ncp)/sqrt(modem->Nfft)*modem->modulate_mask_qpsk(transmitted_bits,0);

            transmitted_symbols.set_length(modulated_ofdm.length()+L+1);
            transmitted_symbols.zeros();

            fading.set_size(L,modulated_ofdm.length());
            fading.zeros();

            channel1.set_length(modulated_ofdm.length());
/*          channel2.set_length(modulated_ofdm.length());
            channel3.set_length(modulated_ofdm.length());
            channel4.set_length(modulated_ofdm.length());
            channel5.set_length(modulated_ofdm.length());
            channel6.set_length(modulated_ofdm.length());
            channel7.set_length(modulated_ofdm.length());
            channel8.set_length(modulated_ofdm.length());
            channel9.set_length(modulated_ofdm.length());
            channel10.set_length(modulated_ofdm.length());
            channel11.set_length(modulated_ofdm.length());
            channel12.set_length(modulated_ofdm.length());
            channel13.set_length(modulated_ofdm.length());
            channel14.set_length(modulated_ofdm.length());
            channel15.set_length(modulated_ofdm.length());
            channel16.set_length(modulated_ofdm.length());*/


            for(int k=0;k<modulated_ofdm.length()/quasi_static;k++){


                channel1.replace_mid(k*quasi_static,ones_c(quasi_static));
                //complex<double> random_complex= randn_c();
                //double canal=sqrt(real(random_complex*conj(random_complex)));
              //channel1.replace_mid(k*quasi_static,canal*ones_c(quasi_static));
              //channel1.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
 /*               channel2.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel3.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel4.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel5.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel6.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel7.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel8.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel9.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel10.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel11.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel12.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel13.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel14.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel15.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));
                channel16.replace_mid(k*quasi_static,randn_c()*ones(quasi_static));*/

            }


            norm_fading=1./sqrt(inv_dB(0)*norm(channel1)*norm(channel1)/modulated_ofdm.length()/*+inv_dB(0)*norm(channel2)*norm(channel2)/modulated_ofdm.length()+inv_dB(0)*norm(channel3)*norm(channel3)/modulated_ofdm.length()+inv_dB(0)*norm(channel4)*norm(channel4)/modulated_ofdm.length()+inv_dB(0)*norm(channel5)*norm(channel5)/modulated_ofdm.length()+inv_dB(0)*norm(channel6)*norm(channel6)/modulated_ofdm.length()+inv_dB(0)*norm(channel7)*norm(channel7)/modulated_ofdm.length()+inv_dB(0)*norm(channel8)*norm(channel8)/modulated_ofdm.length()+inv_dB(0)*norm(channel9)*norm(channel9)/modulated_ofdm.length()+inv_dB(0)*norm(channel10)*norm(channel10)/modulated_ofdm.length()+inv_dB(0)*norm(channel11)*norm(channel11)/modulated_ofdm.length()+inv_dB(0)*norm(channel12)*norm(channel12)/modulated_ofdm.length()+inv_dB(0)*norm(channel13)*norm(channel13)/modulated_ofdm.length()+inv_dB(0)*norm(channel14)*norm(channel14)/modulated_ofdm.length()+inv_dB(0)*norm(channel15)*norm(channel15)/modulated_ofdm.length()+inv_dB(0)*norm(channel16)*norm(channel16)/modulated_ofdm.length()*/);
            fading.set_row(0,norm_fading*channel1);
/*          fading.set_row(1,norm_fading*channel2);
            fading.set_row(2,norm_fading*channel3);
            fading.set_row(3,norm_fading*channel4);
            fading.set_row(4,norm_fading*channel5);
            fading.set_row(5,norm_fading*channel6);
            fading.set_row(6,norm_fading*channel7);
            fading.set_row(7,norm_fading*channel8);
            fading.set_row(8,norm_fading*channel9);
            fading.set_row(9,norm_fading*channel10);
            fading.set_row(10,norm_fading*channel11);
            fading.set_row(11,norm_fading*channel12);
            fading.set_row(12,norm_fading*channel13);
            fading.set_row(13,norm_fading*channel14);
            fading.set_row(14,norm_fading*channel15);
            fading.set_row(15,norm_fading*channel16);*/

            for (int k=0;k<L;k++){
                transmitted_symbols+=concat(zeros_c(k),elem_mult(to_cvec(modulated_ofdm),fading.get_row(k)),zeros_c(L+1-k));
            }
            received_ofdm = channel(transmitted_symbols);

            //received_chips = sum_chips;
            cvec constellation;
            vec estimated_channel;
            double metric;
            //bool is_ofdm=modem->detection(received_ofdm,metric);
            modem->time_offset_estimate=0;
            modem->frequency_offset_estimate=0;
            cvec demodulated_ofdm_symbols=modem->equalizer_fourth_power(received_ofdm,0,estimated_channel);
            received_bits=modem->demodulate_mask_gray_qpsk(demodulated_ofdm_symbols,0,constellation);
            berc.count(transmitted_bits, received_bits);
            ber(i) = berc.get_errorrate();

            cout << "   Iteration " << j + 1 << ": ber = " << berc.get_errorrate() << endl;
            if (berc.get_errors() > MaxNrOfErrors) {
                cout << "Breaking on point " << i + 1 << " with " << berc.get_errors() << " errors." << endl;
                break;
            }

        }

        if (berc.get_errors() < MinNrOfErrors) {
            cout << "Exiting Simulation on point " << i + 1 << endl;
            break;
        }

    }

    //Print results:
    cout << endl;
    cout << "EbN0dB = " << EbN0dB << endl;
    cout << "ber = " << ber << endl;

}
Пример #11
0
vector<double> Plink::calcMantelHaenszel_IxJxK(vector<int> & X,
					       vector<int> & Y,
					       vector<int> & Z)
{
  
  if (X.size() != Y.size() || Y.size() != Z.size() || X.size() != Z.size() )
    error("Internal problem:\n  problem in calcMantelHaenszel_IxJxK()...uneven input columns");
  
  // Determine unique elements
  int nx=0, ny=0, nz=0;
  map<int,int> mx;
  map<int,int> my;
  map<int,int> mz;

  for (unsigned int i=0; i<X.size(); i++)
    {
      if (mx.find(X[i]) == mx.end())
	mx.insert(make_pair(X[i],nx++));

      if (my.find(Y[i]) == my.end())
	my.insert(make_pair(Y[i],ny++));

      if (mz.find(Z[i]) == mz.end())
	mz.insert(make_pair(Z[i],nz++));
    }

  // Generic function to calculate generalized IxJxK CMH
  // Assumes no missing data

  vector< vector<double> > N(nz);             // observed counts
  vector< vector<double> > U(nz);             // expected
  vector< vector< vector<double> > > V(nz);   // variance matrix
  
  vector<vector<double> > Tx(nz); // marginal totals
  vector<vector<double> > Ty(nz); // ..
  vector<double> T(nz);           // totals (per K)
  
  for (int k=0; k<nz; k++)
    {
      Tx[k].resize(nx);
      Ty[k].resize(ny);
      
      N[k].resize((nx-1)*(ny-1));
      U[k].resize((nx-1)*(ny-1));
      V[k].resize((nx-1)*(ny-1));
      for (int k2=0; k2<(nx-1)*(ny-1); k2++)
	{
	  N[k][k2] = U[k][k2] = 0;
	  V[k][k2].resize((nx-1)*(ny-1));
	  for (int k3=0; k3<(nx-1)*(ny-1); k3++)
	    V[k][k2][k3] = 0;
	}
    }
  

  // Consider each observation
  for (int i=0; i<X.size(); i++)
    {
      int vx = mx.find(X[i])->second;
      int vy = my.find(Y[i])->second;
      int vz = mz.find(Z[i])->second;
      
      // exclude nx + ny (upper limits)
      if (vx<nx-1 && vy<ny-1)
	N[vz][ vx + vy*(nx-1) ]++;
      
      Tx[vz][vx]++;
      Ty[vz][vy]++;
      T[vz]++;
    }
  
  
  // Determine valid clusters (at least 2 people)
  vector<bool> validK(nk,false);
  for (int k=0; k<nk; k++)
    if (T[k]>=2) validK[k]=true;
  

  // Calculate expecteds
  for (int k=0; k<nz; k++)
    {
      if (validK[k])
	{
	  for (int ix=0; ix<nx-1; ix++)
	    for (int iy=0; iy<ny-1; iy++)
	      {
		U[k][ix+iy*(nx-1)] = ( Tx[k][ix] * Ty[k][iy] ) / T[k];
		
		for (int ix2=0; ix2<nx-1; ix2++)
		  for (int iy2=0; iy2<ny-1; iy2++)
		    {
		      int dx=0;
		      int dy=0;
		      if (ix==ix2) dx=1;
		      if (iy==iy2) dy=1;
		      V[k][ix + iy*(nx-1)][ix2 + iy2*(nx-1)] = ( ( Tx[k][ix] * ( dx * T[k] - Tx[k][ix2] ) 
								   * Ty[k][iy] * ( dy *T[k] - Ty[k][iy2] )  )
								 / ( T[k]*T[k]*(T[k]-1) ) );
		      if (ix==ix2 && iy==iy2) 
			V[k][ix + iy*(nx-1)][ix2 + iy2*(nx-1)] 
			  = abs(V[k][ix + iy*(nx-1)][ix2 + iy2*(nx-1)]);
		    }
	      }
	}
    }
  

  vector<vector<double> > V0((nx-1)*(ny-1));
  for (int k2=0; k2<(nx-1)*(ny-1); k2++)
    V0[k2].resize((nx-1)*(ny-1));
  vector<double> N0((nx-1)*(ny-1));
  vector<double> U0((nx-1)*(ny-1));

  // Sum N, U and V over K
  for (int k=0; k<nz; k++)
    {
      if (validK[k])
	{
	  for (int i=0; i<(nx-1)*(ny-1); i++)
	    {
	      N0[i] += N[k][i];
	      U0[i] += U[k][i];
	      
	      for (int i2=0; i2<(nx-1)*(ny-1); i2++)
		V0[i][i2] += V[k][i][i2];
	    }
	}
    }
  
  
  bool flag = true;
  vector<double> tmp1((nx-1)*(ny-1),0);
  vector<double> tmp2((nx-1)*(ny-1),0);
  V0 = svd_inverse(V0,flag);
  for (int i=0; i<(nx-1)*(ny-1); i++)
    tmp1[i] = N0[i] - U0[i];
  
  // Matrix mult -- rows by columns
  
  for (int i=0; i<(nx-1)*(ny-1); i++)
    for (int j=0; j<(nx-1)*(ny-1); j++)
      tmp2[j] += tmp1[i] * V0[i][j];
 

  vector<double> result(2);

  // CMH Chi-square
  result[0]=0;
  for (int i=0; i<(nx-1)*(ny-1); i++)
    result[0] += tmp2[i] * tmp1[i];
  
  // DF
  result[1] = (nx-1)*(ny-1);
  return result;

}