void TwoFrameModel::Write(FILE *f) const
{
    fprintf(f, "%d\n", m_num_points);

    fprintf(f, "%0.9f\n", m_angle);

    fprintf(f, "%0.9f\n", m_error);

    for (int i = 0; i < m_num_points; i++) {
        int tr = -1, k1 = -1, k2 = -1;
            
        if (m_tracks != NULL)
            tr = m_tracks[i];
        
        if (m_keys1 != NULL)
            k1 = m_keys1[i];
        
        if (m_keys2 != NULL)
            k2 = m_keys2[i];
        
        fprintf(f, "%d %d %d %0.16e %0.16e %0.16e\n", tr, k1, k2,
                Vx(m_points[i]), Vy(m_points[i]), Vz(m_points[i]));
    }
    
    WriteCamera(f, m_camera0);
    WriteCamera(f, m_camera1);
    
    WriteVector(f, 9, m_C0);
    WriteVector(f, 9, m_C1);
}
void
NgramVector::Serialize(FILE *outFile) const {
    Range r(_length);
    WriteUInt64(outFile, _length);
    WriteVector(outFile, _words[r]);
    WriteVector(outFile, _hists[r]);
}
void TwoFrameModel::WriteSparse(FILE *f)
{
    // WriteCameraPose(f, m_camera0);
    // WriteCameraPose(f, m_camera1);

    /* Compute the camera pose of camera1 relative to camera0 */
    double pos0[3], pos1[3];
    
    // matrix_transpose_product(3, 3, 3, 1, m_camera0.R, m_camera0.t, pos0);
    // matrix_transpose_product(3, 3, 3, 1, m_camera1.R, m_camera1.t, pos1);
    memcpy(pos0, m_camera0.t, 3 * sizeof(double));
    memcpy(pos1, m_camera1.t, 3 * sizeof(double));

    // matrix_scale(3, 1, pos0, -1.0, pos0);
    // matrix_scale(3, 1, pos1, -1.0, pos1);
    
    double diff[3];
    matrix_diff(3, 1, 3, 1, pos1, pos0, diff);
    
    double R1[9], tr[3];
    matrix_transpose_product2(3, 3, 3, 3, m_camera0.R, m_camera1.R, R1);
    // matrix_transpose_product(3, 3, 3, 3, m_camera1.R, m_camera0.R, R1);
    matrix_product(3, 3, 3, 1, m_camera0.R, diff, tr);

    double norm = matrix_norm(3, 1, tr);
    matrix_scale(3, 1, tr, 1.0 / norm, tr);

    double viewdir[3] = { -R1[2], -R1[5], -R1[8] };
    double twist_angle = GetTwist(R1);
    
    /* Compute the distance to the scene */
    double z_avg = 0.0;
    
    for (int p = 0; p < m_num_points; p++) {
        v3_t &pt = m_points[p];

        double diff1[3], diff2[3];
        matrix_diff(3, 1, 3, 1, pt.p, pos0, diff1);
        matrix_diff(3, 1, 3, 1, pt.p, pos1, diff2);

        double dist1 = matrix_norm(3, 1, diff1);
        double dist2 = matrix_norm(3, 1, diff2);

        z_avg += 0.5 * (dist1 + dist2) / norm;
    }

    z_avg /= m_num_points;
    
    WriteVector(f, 9, R1);
    /* Write the viewing direction */
    // WriteVector(f, 3, viewdir);
    /* Write the twist angle */
    // fprintf(f, "%0.8f\n", twist_angle);
    /* Write the translation */
    WriteVector(f, 3, tr);

    fprintf(f, "%0.6f\n", z_avg);
}
void TwoFrameModel::WriteBrief(FILE *f) const
{
    fprintf(f, "%d\n", m_num_points);

    fprintf(f, "%0.5f\n", m_angle);

    fprintf(f, "%0.5f\n", m_error);
    
    WriteVector(f, 9, m_C0);
    WriteVector(f, 9, m_C1);
}
Beispiel #5
0
void CSave::WritePositionVector( const char *pname, const Vector &value )
{

	if( m_pdata && m_pdata->fUseLandmark )
	{
		Vector tmp = value - m_pdata->vecLandmarkOffset;
		WriteVector( pname, tmp );
	}

	WriteVector( pname, value );
}
Beispiel #6
0
END_TEST

START_TEST( test_NormalDirection )
{
  PetscErrorCode ierr;
  int d1 = 210, d2 = 210;
  LevelSet2D ls;
  
  ierr = CreateLevelSet2D(d1, d2, &ls); CHKERRQ(ierr);
//  ierr = LevelSetInitializeToCircle(ls, 10, 5, 3.2); CHKERRQ(ierr);
  LevelSetInitializeToStar(ls,PETSC_DECIDE,PETSC_DECIDE,PETSC_DECIDE);
  ierr = WriteVector("initls",ls->g2d->v); CHKERRQ(ierr);
  ierr = UpdateIrregularNodeList(ls); CHKERRQ(ierr);
  GArray *ga = ls->irregularNodes;
  LocalCoor2D lc;
  ierr = LocalCoor2DCreate(12, &lc); CHKERRQ(ierr);
  IrregularNode *n;
  for( int i = 0; i < ga->len; i++ )
  {
    n = &g_array_index( ga, IrregularNode, i); 
    PetscReal nx, ny, h;
      
    nx = Bilinear2D(GridFunction2D_DerivX, ls->g2d, n->x+n->ox, n->y+n->oy);
    ny = Bilinear2D(GridFunction2D_DerivY, ls->g2d, n->x+n->ox, n->y+n->oy);
    h = sqrt( nx*nx + ny*ny );
      
    n->nx = nx / h;
    n->ny = ny / h;
  }
  ierr = IrregularNodeListWrite(ls,0); CHKERRQ(ierr);
}
Beispiel #7
0
	void Int_SVQ(u32 op)
	{
		int imm = (signed short)(op&0xFFFC);
		int rs = _RS;
		int vt = (((op >> 16) & 0x1f)) | ((op&1) << 5);

		u32 addr = R(rs) + imm;

		switch (op >> 26)
		{
		case 53: //lvl.q/lvr.q
			if (addr & 0x3)
			{
				_dbg_assert_msg_(CPU, 0, "Misaligned lvX.q");
			}
			if ((op&2) == 0)
			{
				// It's an LVL
				float d[4];
				ReadVector(d, V_Quad, vt);
				int offset = (addr >> 2) & 3;
				for (int i = 0; i < offset + 1; i++)
				{
					d[3 - i] = Memory::Read_Float(addr - i * 4);
				}
				WriteVector(d, V_Quad, vt);
			}
			else
			{
/* PutVFloor: output variance floor vectors */
void PutVFloor(void)
{
   int i,s;
   char outfn[MAXSTRLEN],vName[32],num[10];
   FILE *f;
   Vector v;
   
   MakeFN("vFloors",outDir,NULL,outfn);
   if ((f = fopen(outfn,"w")) == NULL)
      HError(2011,"PutVFloor: cannot create %s",outfn);
   for (s=1; s <= hset.swidth[0]; s++) {
      v = CreateVector(&gstack,hset.swidth[s]);
      sprintf(num,"%d",s); 
      strcpy(vName,"varFloor"); strcat(vName,num);
      fprintf(f,"~v %s\n",vName);
      if (fullcNeeded[s])              
         TriDiag2Vector(accs[s].squareSum.inv,v);
      else
         CopyVector(accs[s].fixed.var,v);
      for (i=1; i<=hset.swidth[s]; i++)
         v[i] *= vFloorScale;
      fprintf(f,"<Variance> %d\n",hset.swidth[s]);
      WriteVector(f,v,FALSE);
      FreeVector(&gstack,v);
   }
   fclose(f);
   if (trace&T_TOP)
      printf("Var floor macros output to file %s\n",outfn);
}
Beispiel #9
0
int main(int argc, char **argv) {
    if (argc == 1) {
	PrintHelp();
	return 0;
    }
    int network = atoi(argv[1]);
    int num_comms = 3;
    int triple_type = D3CS;
    int cut_type = D3C_COND;
    std::string name = NetworkStr(network);

    {
	Network net = GetNetwork(network, triple_type);
	Cutter cutter(net, 0, cut_type, name + "_cocluster_u");

	std::string file = "data/" + name + "_u";
	std::vector<double> vals = ReadVector<double>(file);
	Vector<double> u_vals(vals.size());
	for (int i = 0; i < vals.size(); ++i) {
	    u_vals(i) = vals[i];
	}

	std::vector<int> order = GetSortedOrder(u_vals);
	WriteVector(order, name + "_cocluster_u_order.txt");
	//std::vector<int> cut = cutter.GetCut(order);
    }

    {
	Network net = GetNetwork(network, triple_type);
	Cutter cutter(net, 0, cut_type, name + "_cocluster_v");

	std::string file = "data/" + name + "_v";
	std::vector<double> vals = ReadVector<double>(file);
	Vector<double> v_vals(vals.size());
	for (int i = 0; i < vals.size(); ++i) {
	    v_vals(i) = vals[i];
	}

	std::vector<int> order = GetSortedOrder(v_vals);
	WriteVector(order, name + "_cocluster_v_order.txt");
	//std::vector<int> cut = cutter.GetCut(order);
    }

    std::cout << "END ---------" << std::endl;
}
Beispiel #10
0
/* StoreTree: store each node as an entry */
static void StoreTree(FILE *f, VQNode n, CovKind ck, short s)
{
   if (n != NULL){
      fprintf(f,"%d %d %d %d %d\n",s,n->vqidx,n->nid,n->lid,n->rid);
      WriteVector(f,n->mean,FALSE);
      switch(ck){
      case NULLC:
         break;
      case INVDIAGC:
         WriteVector(f,(Vector)n->cov.var,FALSE);
         break;
      case FULLC:
         WriteTriMat(f,(TriMat)n->cov.inv,FALSE);
         break;
      }
      fprintf(f,"\n");
      StoreTree(f,n->left,ck,s);
      StoreTree(f,n->right,ck,s);
   }
}
Beispiel #11
0
bool CGraphmatFile :: LoadFileToGraphan (const string&  CommandLine)
{
    try
    {
        m_SourceFileName = CommandLine.c_str();
        m_GraFileName = MakeFName (m_SourceFileName,"gra");
        m_XmlMacSynName = MakeFName (m_SourceFileName,"xml");
        m_SaveTxtName = MakeFName (m_SourceFileName,"tds");

        if (IsHtmlFile(m_SourceFileName))
        {
            HTML Convert(m_SourceFileName);
            string Text = Convert.getText();

            if (!InitInputBuffer(Text))
            {
                m_LastError = Format("Cannot init inpur buffer for %i bytes", Text.length());
                return false;
            }

            if   (m_bSaveHtmlFileToTdsFile)
                WriteVector(m_SaveTxtName, GetInputBuffer());
        }
        else
        {
            if (access(m_SourceFileName.c_str(), 04) != 0) return  false;
            string Text;
            LoadFileToString(m_SourceFileName, Text);
            if (!InitInputBuffer(Text))
            {
                m_LastError = Format("Cannot init inpur buffer for %i bytes", Text.length());
                return false;
            };

        };



        return  GraphmatMain ();

    }
    catch (CExpc& C)
    {
        m_LastError = C.m_ErrorCode;
        return false;
    }
    catch (...)
    {
        m_LastError = "general exception";
        return false;
    };
};
Beispiel #12
0
END_TEST

START_TEST( WriteVector_test )
{
  PetscErrorCode ierr;
  
  Vec v;
  VecCreate( PETSC_COMM_SELF, &v);
  VecSetSizes(v, 10, 10);
  VecSetType(v, VECSEQ );
  VecSet(v, one);
  
  ierr = WriteVector("testwrite.bin", v); CHKERRQ(ierr);
}
int WriteVectorDistribution(const long int *X, const char *name, long l, int P, FILE *fp, const struct opts *pOptions) {

    /* This function writes the owners of the vector components to a file.
       Input: l is the number of vector components.
              P is the number of processors.
              X is an array of length l, containing the owners 
                   of the vector components. 
              The input numbering is 0-based: 0 <= X[i] < P, for 0 <= i < l.
       The output file format is:
              1 line with l , P
              1 line per vector component, giving the index i and the owner X[i].
              The output numbering is 1-based: 1 <= X[i] <= P, for 1 <= i <= l.
              This numbering is consistent with the Matrix Market format. */

    return WriteVector( X, 0, name, l, P, fp, pOptions );
} /* end WriteVectorDistribution */
Beispiel #14
0
void debug_stream_test_cb (puObject* obj)
{
  SStream* s = new SStream;
  strncpy (s->filename, "teststream.txt",(PATH_MAX-1));
  strncpy (s->mode, "w",3);
  OpenStream (s);

  WriteComment ("Comment...testing testing testing", s);
  WriteComment ("", s);
  WriteTag ('bgno', "---- object ----", s);
  WriteTag ('bgno', "---- nested Object ----", s);
  WriteTag ('int_', "---- int ----", s);
  int i = 500;
  WriteInt (&i, s);
  WriteTag ('uint', "---- unsigned int ----", s);
  unsigned int ui = 12345678;
  WriteUInt (&ui, s);
  float f = 12345.67f;
  WriteTag ('flot', "---- float ----", s);
  WriteFloat (&f, s);
  double d = 987654.3210;
  WriteTag ('dubl', "---- double ----", s);
  WriteDouble (&d, s);
  WriteTag ('stng', "---- string ----", s);
  WriteString ("This a string", s);
  SVector v;
  v.x = 1.0;
  v.y = 2.0;
  v.z = 3.0;
  WriteTag ('vect', "--- vector ----", s);
  WriteVector (&v, s);
  SPosition pos;
  pos.lat = 1000.0;
  pos.lon = 2000.0;
  pos.alt = 3000.0;
  WriteTag ('posn', "---- position ----", s);
  WritePosition (&pos, s);
  SMessage mesg;
  WriteTag ('mesg', "---- message ----", s);
  WriteMessage (&mesg, s);
  WriteTag ('endo', s);
  WriteTag ('endo', s);

  CloseStream (s);
  delete s;
}
Beispiel #15
0
inline void WriteStubGate(Process const& process,
                          void* address,
                          void* stub,
                          void* get_orig_user_ptr_ptr_fn)
{
  using StubT = typename PatchDetourStub<TargetFuncT>;
#if defined(HADESMEM_DETAIL_ARCH_X64)
  auto const stub_gate = GenStubGate64(stub, get_orig_user_ptr_ptr_fn);
#elif defined(HADESMEM_DETAIL_ARCH_X86)
  auto const stub_gate = GenStubGate32(stub, get_orig_user_ptr_ptr_fn);
#else
#error "[HadesMem] Unsupported architecture."
#endif
  WriteVector(process, address, stub_gate);
  WriteJump(process,
            static_cast<std::uint8_t*>(address) + stub_gate.size(),
            &StubT::Stub,
            true,
            nullptr);
  FlushInstructionCache(process, address, stub_gate.size());
}
Beispiel #16
0
inline std::size_t
  WriteCall(Process const& process,
            void* address,
            void* target,
            std::vector<std::unique_ptr<Allocator>>& trampolines)
{
  HADESMEM_DETAIL_TRACE_FORMAT_A("Address = %p, Target = %p", address, target);

  std::vector<std::uint8_t> call_buf;

// TODO: Avoid using a trampoline where possible.
#if defined(HADESMEM_DETAIL_ARCH_X64)
  std::unique_ptr<Allocator> trampoline = AllocatePageNear(process, address);

  PVOID tramp_addr = trampoline->GetBase();

  HADESMEM_DETAIL_TRACE_FORMAT_A("Using trampoline call. Trampoline = %p.",
                                 tramp_addr);

  Write(process, tramp_addr, reinterpret_cast<std::uintptr_t>(target));

  trampolines.emplace_back(std::move(trampoline));

  call_buf = GenCallTramp64(address, tramp_addr);
  HADESMEM_DETAIL_ASSERT(call_buf.size() == PatchConstants::kCallSize64);
#elif defined(HADESMEM_DETAIL_ARCH_X86)
  (void)trampolines;
  HADESMEM_DETAIL_TRACE_A("Using relative call.");
  call_buf = GenCall32(address, target);
  HADESMEM_DETAIL_ASSERT(call_buf.size() == PatchConstants::kCallSize32);
#else
#error "[HadesMem] Unsupported architecture."
#endif

  WriteVector(process, address, call_buf);

  return call_buf.size();
}
Beispiel #17
0
/* WriteParms: write generated parameter vector sequences */
void WriteParms(char *labfn, GenInfo * genInfo)
{
   int p, t, v, k;
   char ext[MAXSTRLEN], fn[MAXFNAMELEN];
   float ig;
   Vector igvec;
   TriMat igtm;
   FILE *parmfp = NULL, *pdffp = NULL;
   Boolean isPipe1, isPipe2;
   PdfStream *pst;

   /* get ignore value for MSD */
   ig = ReturnIgnoreValue();

   /* save generated parameters */
   for (p = 1; p <= genInfo->nPdfStream[0]; p++) {
      /* p-th PdfStream */
      pst = &(genInfo->pst[p]);

      /* create ignore value vector/triangular matrix */
      igvec = CreateVector(&genStack, pst->vSize);
      igtm = CreateTriMat(&genStack, pst->vSize);
      for (v = 1; v <= pst->vSize; v++) {
         igvec[v] = ig;
         for (k = 1; k <= v; k++)
            igtm[v][k] = ig;
      }

      /* open file pointer for saving generated parameters */
      MakeFN(labfn, genDir, pst->ext, fn);
      if ((parmfp = FOpen(fn, NoOFilter, &isPipe1)) == NULL)
         HError(9911, "WriteParms: Cannot create ouput file %s", fn);

      /* open file pointer for saving pdf parameters */
      if (outPdf) {
         sprintf(ext, "%s_%s", pst->ext, pdfExt);
         MakeFN(labfn, genDir, ext, fn);
         if ((pdffp = FOpen(fn, NoOFilter, &isPipe2)) == NULL)
            HError(9911, "WriteParms: Cannot create output file %s", fn);
      }

      /* output generated parameter sequence */
      for (t = pst->t = 1; t <= genInfo->tframe; t++) {
         if (pst->ContSpace[t]) {
            /* output generated parameters */
            WriteVector(parmfp, pst->C[pst->t], inBinary);

            /* output pdfs */
            if (outPdf) {
               WriteVector(pdffp, pst->mseq[pst->t], inBinary);
               if (pst->fullCov)
                  WriteTriMat(pdffp, pst->vseq[pst->t].inv, inBinary);
               else
                  WriteVector(pdffp, pst->vseq[pst->t].var, inBinary);
            }

            pst->t++;
         } else {
            /* output ignoreValue symbol for generated parameters */
            WriteFloat(parmfp, &igvec[1], pst->order, inBinary);

            /* output ignoreValue symbol for pdfs */
            if (outPdf) {
               WriteVector(pdffp, igvec, inBinary);
               if (pst->fullCov)
                  WriteTriMat(pdffp, igtm, inBinary);
               else
                  WriteVector(pdffp, igvec, inBinary);
            }
         }
      }

      /* close file pointer */
      if (outPdf)
         FClose(pdffp, isPipe2);
      FClose(parmfp, isPipe1);

      /* free igvec */
      FreeVector(&genStack, igvec);
   }

   return;
}
Beispiel #18
0
int main(int argc, char **args)
{
  PetscErrorCode  ierr;
  
  ierr = PetscInitialize(&argc, &args, (char *) 0, ""); CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, "Start\n"); CHKERRQ(ierr);
  
  int d1 = 200, d2 = 200;
  LevelSet2D ls;
  CreateLevelSet2D(d1,d2,&ls);
//  LevelSetInitializeToCircle(ls, PETSC_DECIDE,PETSC_DECIDE,PETSC_DECIDE);
  LevelSetInitializeToStar(ls,  PETSC_DECIDE,PETSC_DECIDE,PETSC_DECIDE);
  
  Grid2D rhs;
  CreateGrid2D(d1,d2,&rhs);
  
  IrregularNode *n;
  int ni, nj, k;
  const int nei[5][2] = {1,0, 0,1, -1,0, 0,-1, 0,0};
  PetscReal ox, oy;
  for (int i = 0; i < ls->irregularNodes->len; ++i)
  {
    n = &g_array_index(ls->irregularNodes, IrregularNode, i);
    
    for (int k = 0; k < 5; ++k)
    {
      ni = n->x+nei[k][0];
      nj = n->y+nei[k][1];
      OrthogonalProjection( ls->g2d->v2, ni, nj, &ox, &oy  );
      n->utilde[k] = Bilinear2D( GridFunction2D_Curv, ls->g2d, ni+ox, nj+oy );
      
      /* Correction terms
      C = 0;
      if( -1 * phi[ni][nj] * phi[i][j] )
      {
        C += gamma[k] * PetscSqr( phi[ni][nj] / () ) * (F[ni][nj] - F[i][j]) / 2;
      }
      */
    }
  }

  
  /* print subirregular nodes
  for (int i = 0; i < ls->irregularNodes->len; ++i)
  {
    n = &g_array_index(ls->irregularNodes, IrregularNode, i);
    
    for (k = 0; k < 4; ++k)
    {
      printf("{%d,%d},",n->x+nei[k][0],n->y+nei[k][1]);
    }
  }*/
  
  PetscReal lut; // laplace( u-tilde )
  PetscReal luh; // laplace( u-hat )
    
  for (int i = 0; i < ls->irregularNodes->len; ++i)
  {
    n = &g_array_index(ls->irregularNodes, IrregularNode, i);
    
    // H * laplace( u-tilde )
    lut = 0;
    if( n->sign > 0.)
    {
      for (k = 0; k < 4; ++k)
      {
        lut += n->utilde[k];
      }
      lut -= 4 * n->utilde[4];
    }
    
    // laplace( u-hat ) = laplace( H * u-tilde )
    luh = 0;
    for (k = 0; k < 4; ++k)
    {
      ni = n->x + nei[k][0];
      nj = n->y + nei[k][1];
      if( ls->g2d->v2[ni][nj] > 0 )
      {
        luh += n->utilde[k];
      }
    }
    if( n->sign > 0 )
    {
      luh -= 4 * n->utilde[4];
    }
    
    rhs->v2[n->x][n->y] = -lut + luh; 
    
  }
  
  
  WriteVector("rhs",rhs->v);
  
  WriteVector("phi",ls->g2d->v);
  
  
  
  ierr = PetscPrintf(PETSC_COMM_WORLD, "End\n"); CHKERRQ(ierr);
  ierr = PetscFinalize(); CHKERRQ(ierr);
  return 0; 
}
Beispiel #19
0
int main(int argc, char **argv) {

    /* This function is the main function, called mondriaan. It partitions
       a sparse matrix, a dense input vector, and a dense output vector
       for the purpose of parallel sparse matrix-vector multiplication u = A*v.

       The function tries to minimise the total communication volume
       by suitably partitioning the matrix, while keeping the computation
       load imbalance withing a user-specified fraction epsilon.
       For the resulting communication volume, it tries to balance
       the communication work among the processors by suitably
       partitioning the vectors. The partitioning of the input and output
       vectors can either be done independently, or by imposing
       distr(u) = distr(v).

       The sparse matrix is read from file using the Matrix Market (MM) format.
       Its partitioning is written to file using a variant of the MM format,
       where all nonzeros belonging to the same processor are listed together.

       If the input file is called
           pi.mtx
       and 4 processors are required, the following output files are produced:
           pi.mtx-P4 containing the matrix distribution
           pi.mtx-v4                input vector distribution
           pi.mtx-u4                output vector distribution
           pi.mtx-C4                Cartesian submatrices corresponding
                                    to the matrix distribution
       Furthermore, useful information on the partitioning process
       and the result, such as the load imbalance and communication
       volume obtained, is written to standard output.

       The sparse matrix partitioner can also be used for partitioning
       hypergraphs. To do this, Mondriaan must be used in 1D column mode. 
       Matrix columns then represent hypergraph vertices; they can be given
       integer weights. Matrix rows then represent hyperedges; they cannot
       be given weights.

       The following additional operations are carried out by the main program:
           - timing the matrix and vector partitionings
           - removing duplicate nonzeros
           - (optionally) checking whether the matrix is structurally symmetric
           - (optionally) expanding a symmetric matrix stored in lower
             triangular format to a fully stored matrix
           - (optionally) adding diagonal dummy nonzeros to a square matrix
             to make the diagonal completely nonzero (thereby facilitating
             the vector distribution with distr(u) = distr(v)).

       All partitioning options and parameters can be set using
       the file mondriaan.defaults (provided the main function is compiled
       with the name mondriaan.) If no such file exists, it is created with
       sensible defaults.

       If the input matrix has already been partitioned, it will be
       partitioned again, from scratch.
 */

    struct opts Options; /* The Mondriaan options */
    struct sparsematrix A; /* The Matrix;-) */

    long MinNrNzElts, MaxNrNzElts; /* minimum, maximum number of nonzero elements 
                                       per processor */
    double AvgNrNzElts; /* average number of nonzero matrix elements per processor */

    long MinWeight, MaxWeight, TotWeight; /* minimum, maximum, total column weight */
    double AvgWeight;                    /* average column weight */
    long weight, i, j;
    unsigned long int ui;
    long int *temp;
    long ComU, ComV; /* communication cost for vectors u, v  */
    long q, nzq;     /* processor number and its corresponding number of nonzeros */
    int weighted, symmetric; /* boolean registering whether the input matrix
                                 was weighted, symmetric */

    long int *u_proc, *v_proc;   /* vector distribution for u, v */
    char output[MAX_WORD_LENGTH]; /* filename of the output */
    char EMMcomment[2000]; /* Comments in EMM one-file output */
    
    long int **row_perms = NULL, **col_perms = NULL; /* Will store local to global index info */

    /* Below is used for Extended Matrix-Market one-file output */
    long int *inv_count, **row_local2proc, **row_local2index, **col_local2proc, **col_local2index;

    FILE *File = NULL;
    char stdinName[] = "stdin";
    
    /* Timing variables */
    clock_t starttime, endtime;
    double cputime;
#ifdef UNIX
    struct timeval starttime1, endtime1;
#endif

    /* Get the parameters from the command line and initialise Options */
    SetDefaultOptions(&Options);
    
    if (!SetOptionsFromFile(&Options, "Mondriaan.defaults")) {
        fprintf(stderr, "main(): warning, cannot set options from 'Mondriaan.defaults', using default options and creating standard 'Mondriaan.defaults'!\n");
        
        File = fopen("Mondriaan.defaults", "w");
        
        if (File != NULL) {
            ExportDefaultOptions(File);
            SetDefaultOptions(&Options);
            fclose(File);
        }
        else {
            fprintf(stderr, "main(): Unable to create 'Mondriaan.defaults'!\n");
        }
    }
    
    if (!GetParameters(&Options, argc, argv)) {
        fprintf(stderr, "main(): invalid command line parameters!\n");
        exit(-1);
    }
    
    if (!ApplyOptions(&Options)) {
        fprintf(stderr, "main(): could not apply given options!\n");
        exit(-1);
    }
    
    /* Read matrix file from disk or standard input. */
    if (!strcmp(Options.matrix, "-") || !strcmp(Options.matrix, "stdin")) {
        if (!MMReadSparseMatrix(stdin, &A)) {
            fprintf(stderr, "main(): Could not read matrix from standard input!\n");
            exit(-1);
        }
        
        Options.matrix = stdinName;
    }
    else {
        File = fopen(Options.matrix, "r");
    
        if (!File) {
            fprintf(stderr, "main(): Unable to open '%s' for reading!\n", Options.matrix);
            exit(-1);
        }
        
        if (!MMReadSparseMatrix(File, &A)) {
            fprintf(stderr, "main(): Could not read matrix!\n");
            exit(-1);
        }
        
        fclose(File);
    }
  
#ifdef INFO
    printf("\nUsing Mondriaan version %s.\n\n", MONDRIAANVERSION);
    printf("\n**************************************************************\n");
    printf("Problem statistics:\n");
    printf("  Matrix:           : %s\n",Options.matrix);
    printf("  %s %s %s %s %s\n", A.Banner,A.Object,A.Format,A.Field,A.Symmetry);
    printf("  m = Nr rows       : %ld\n", A.m); 
    printf("  n = Nr columns    : %ld\n", A.n); 
    printf("  nz = Nr nonzeros  : %ld\n", A.NrNzElts);
  
    /* Check if matrix A is structurally symmetric */
    if (SparseMatrixStructurallySymmetric(&A))
        printf("  Matrix is structurally symmetric\n\n");
    else
        printf("  Matrix is structurally unsymmetric\n\n");
#endif

    /* Remove duplicate nonzeros by adding them */
    if (!SparseMatrixRemoveDuplicates(&A)) {
        fprintf(stderr, "main(): Unable to remove duplicates!\n");
        exit(-1);
    }

    /* Check if matrix A is already distributed */
    if (A.MMTypeCode[0] == 'D') {
        /* Matrix will be partitioned again */
        fprintf(stderr, "Warning: Matrix '%s' already distributed !\n", 
                Options.matrix);
        fprintf(stderr, "         (Ignoring current partitions)\n"); 
        
        A.NrProcs = 0;
        if (A.Pstart != NULL)
            free(A.Pstart);
        A.Pstart = NULL;
    }
   
    /* Check if matrix is weighted (thus representing a hypergraph).
       In that case, it must have n column weights (representing vertex weights), 
       0 row weights and the split strategy must be onedimcol */

    if (A.MMTypeCode[0] == 'W' && A.NrColWeights != A.n) {
        fprintf(stderr, "main(): Weighted matrix with NrColWeights != n!\n");
        exit(-1);
    }

    if (A.MMTypeCode[0] == 'W' && A.NrRowWeights != 0) {
        fprintf(stderr, "Warning: Matrix '%s' has row weights!\n",
                Options.matrix);
        fprintf(stderr, "         Row-weighted column partitioning not yet implemented\n");
        fprintf(stderr, "         (Ignoring row weights)\n");
                
        A.NrRowWeights = 0;
        if (A.RowWeights != NULL)
            free(A.RowWeights);
        A.RowWeights = NULL;
    }

    if (A.MMTypeCode[0] == 'W' && Options.SplitStrategy != OneDimCol) {
        fprintf(stderr, "Warning: Matrix '%s' is a weighted matrix!\n", Options.matrix);
        fprintf(stderr, "         must be partitioned by onedimcol strategy\n");
        fprintf(stderr, "         (Ignoring requested split strategy)\n");
        Options.SplitStrategy = OneDimCol;
    }

    /* Register whether the input matrix was weighted, since the object type code will
       be changed by the partitioning procedure to the code 'D' for a distributed matrix */
    if (A.MMTypeCode[0] == 'W')
        weighted = TRUE;
    else
        weighted = FALSE;
  
    /* Register whether the input matrix was symmetric, since the symmetry type code will
       be changed by the conversion to full, to the code 'G' for a general matrix */
    if (A.m == A.n && 
         (A.MMTypeCode[3]=='S' || A.MMTypeCode[3]=='K' || A.MMTypeCode[3]=='H')) {
        symmetric = TRUE; 
    } else {
        symmetric = FALSE;
        if (Options.SplitStrategy == SFineGrain) {
            fprintf(stderr, "Error: Symmetric finegrain can only be used on symmetric input matrices!\n");
            exit(-1);
        }
    }
    
    if (symmetric) {
        if (Options.SymmetricMatrix_UseSingleEntry == SingleEntNo)
            SparseMatrixSymmetric2Full(&A); 
        else if (Options.SplitStrategy == SFineGrain)
            SparseMatrixSymmetricRandom2Lower(&A);
        else if (Options.SymmetricMatrix_SingleEntryType == ETypeRandom)
            SparseMatrixSymmetricLower2Random(&A);
    }

    if (Options.SplitStrategy == SFineGrain && Options.SymmetricMatrix_SingleEntryType == ETypeRandom)
        printf("Warning: Symmetric finegrain requires lower-triangular format of symmetric matrix;\n         Random single entry type option is overridden.\n");
  
    /* If the matrix is square, add the dummies if requested.
       This may lead to an enhanced vector distribution in the case of
       an equal distribution of the input and output vectors.  */
    if (A.m == A.n && 
         Options.SquareMatrix_DistributeVectorsEqual == EqVecYes &&
         Options.SquareMatrix_DistributeVectorsEqual_AddDummies == DumYes)
        AddDummiesToSparseMatrix(&A);
  
    /* Set the number of processors */
    A.NrProcs = Options.P;
    
#ifdef INFO
    printf("  P = Nr processors : %d\n", A.NrProcs);
    printf("  Nr dummies added  : %ld\n", A.NrDummies);
    printf("  allowed imbalance : %g %c\n", 100*Options.eps, '%');
    printf("\n****** Mondriaan matrix distribution ******\n\n");
#endif

    /* Initialise Pstart with all nonzeros in processor 0 */
    A.Pstart = (long *) malloc((A.NrProcs+1) * sizeof(long));
    if (A.Pstart == NULL) {
        fprintf(stderr, "main(): Not enough memory for Pstart!\n");
        exit(-1);
    }
    
    A.Pstart[0] = 0;
    for (q = 1; q <= A.NrProcs; q++)
        A.Pstart[q] = A.NrNzElts;
  
    /**** Distribute the matrix (and time it) ****/
    starttime = clock();
#ifdef UNIX
    gettimeofday(&starttime1, NULL);
#endif
  
    if (!DistributeMatrixMondriaan(&A, A.NrProcs, Options.eps, &Options, 0)) {
        fprintf(stderr, "main(): Unable to distribute matrix!\n");
        exit(-1);
    }
    
    endtime = clock();
#ifdef UNIX
    gettimeofday(&endtime1, NULL);
#endif
    cputime = ((double) (endtime - starttime)) / CLOCKS_PER_SEC;
  
#ifdef TIME
    printf("  matrix distribution CPU-time    : %f seconds\n", cputime); 
#ifdef UNIX 
    printf("  matrix distribution elapsed time: %f seconds\n",
             (endtime1.tv_sec - starttime1.tv_sec) +
             (endtime1.tv_usec - starttime1.tv_usec) / 1000000.0); 
#endif 
    fflush(stdout);
#endif 
  
    /* Remove the dummies */
    if (A.m == A.n &&
         Options.SquareMatrix_DistributeVectorsEqual == EqVecYes && 
         Options.SquareMatrix_DistributeVectorsEqual_AddDummies == DumYes)
        RemoveDummiesFromSparseMatrix(&A);
  
    /* Print information about the number of matrix elements */
    AvgNrNzElts = (double) A.NrNzElts / A.NrProcs;
    MinNrNzElts = LONG_MAX;
    MaxNrNzElts = LONG_MIN;
    for (q = 0; q < A.NrProcs; q++) {
        nzq = A.Pstart[q+1] - A.Pstart[q];
        if (nzq < MinNrNzElts)
            MinNrNzElts = nzq;
        if (nzq > MaxNrNzElts)
            MaxNrNzElts = nzq;
    }

#ifdef INFO
    printf("  Nr nonzero matrix elements:\n");
    printf("    tot         : %ld \n", A.NrNzElts);
    printf("    avg = tot/P : %g  \n", AvgNrNzElts);
    printf("    max         : %ld \n", MaxNrNzElts);
    printf("    min         : %ld \n", MinNrNzElts);
    printf("    imbalance   : %g %c\n",
                100 * (MaxNrNzElts/AvgNrNzElts - 1.0), '%');
#endif

    if (weighted){
        A.MMTypeCode[0] = 'W'; /* temporarily, needed for computing weights */
        TotWeight = ComputeWeight(&A, 0, A.NrNzElts-1, NULL, &Options);
        AvgWeight = (double) TotWeight / A.NrProcs;
        MinWeight = LONG_MAX;
        MaxWeight = LONG_MIN;
        for (q = 0; q < A.NrProcs; q++) {
            weight = ComputeWeight(&A, A.Pstart[q], A.Pstart[q+1]-1, NULL, &Options);
            if (weight < MinWeight)
                MinWeight = weight;
            if (weight > MaxWeight)
                MaxWeight = weight;
        }
        A.MMTypeCode[0] = 'D'; /* back to distributed matrix */

#ifdef INFO
        printf("  Vertex (column) weight:\n");
        printf("    tot         : %ld \n", TotWeight);
        printf("    avg = tot/P : %g  \n", AvgWeight);
        printf("    max         : %ld \n", MaxWeight);
        printf("    min         : %ld \n", MinWeight);
        printf("    imbalance   : %g %c\n",
                    100 * (MaxWeight/AvgWeight - 1.0), '%');
#endif
    }

    /* Convert randomly represented symmetric matrix to standard
       lower triangular form */
    if (symmetric &&
         Options.SymmetricMatrix_UseSingleEntry == SingleEntYes &&
         Options.SymmetricMatrix_SingleEntryType == ETypeRandom)
              SparseMatrixSymmetricRandom2Lower(&A);
 
    /* Writing (distributed) matrix info */
    if( Options.OutputMode == MultipleFiles ) {
 
        /* Write the distributed matrix to file */
        sprintf(output, "%s-P%d", Options.matrix, A.NrProcs);
        File = fopen(output, "w");
        if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
        else {
            MMWriteSparseMatrix(&A, File, NULL, &Options);
            fclose(File);
        }

        /* Commit to permutation */
        if (A.row_perm_inv != NULL && A.col_perm_inv != NULL) {
            for( i=0; i<A.NrNzElts; i++ ) {
                A.i[ i ] = A.row_perm_inv[ A.i[ i ] ];
                A.j[ i ] = A.col_perm_inv[ A.j[ i ] ];
            }
        }
 
        /* Write permuted matrix */
        sprintf(output, "%s-reor-P%d", Options.matrix, A.NrProcs);
        File = fopen(output, "w");
        A.MMTypeCode[0] = 'M';
        if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
        else {
            MMWriteSparseMatrix(&A, File, NULL, &Options);
            fclose(File);
        }
        A.MMTypeCode[0] = 'D';

        /* Write out block information */
        if (A.rowBoundaries) {
            if (remembrance_get( A.rowBoundaries )==NULL) {
                fprintf(stderr, "main(): Error during read-out of row boundaries\n");
                exit( -1 );
            }
            sprintf(output, "%s-rowblocks%d", Options.matrix, A.NrProcs);
            File = fopen(output, "w");
            if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
            else {
                remembrance_write(A.rowBoundaries, File);
                fclose(File);
            }
        }
        if (Options.SplitStrategy != SFineGrain)
            if (A.colBoundaries) {
                if (remembrance_get( A.colBoundaries )==NULL) {
                    fprintf(stderr, "main(): Error during read-out of column boundaries\n");
                    exit( -1 );
                }
                sprintf(output, "%s-colblocks%d", Options.matrix, A.NrProcs);
                File = fopen(output, "w");
                if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
                else {
                   remembrance_write(A.colBoundaries, File);
                   fclose(File);
                }
            }
        

        /* Undo commit to permutation */
        if (A.row_perm_inv != NULL && A.col_perm_inv != NULL) {
            for( i=0; i<A.NrNzElts; i++ ) {
                A.i[ i ] = A.row_perm[ A.i[ i ] ];
                A.j[ i ] = A.col_perm[ A.j[ i ] ];
            }
        }

        /* Write out local matrix format */
        row_perms = malloc( (A.NrProcs+1) * sizeof( long int * ) );
        col_perms = malloc( (A.NrProcs+1) * sizeof( long int * ) );
        if( !row_perms || !col_perms || 
            !SparseMatrixOriginal2Local(&A, row_perms, col_perms) ) {
            fprintf(stderr, "main(): Unable to transform to local view!");
            exit(-1);
        }
        sprintf(output, "%s-local%d", Options.matrix, A.NrProcs);
        File = fopen(output, "w");
        if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
        else {
            MMWriteSparseMatrix(&A, File, NULL, &Options);
            fclose(File);
        }

        /* Transform matrix back */
        for( i=0; i<A.NrProcs; i++ )
            for(j=A.Pstart[i]; j<A.Pstart[i+1]; j++ ) {
                A.i[j] = row_perms[i][ A.i[j] ];
                A.j[j] = col_perms[i][ A.j[j] ];
            }
        A.ViewType = ViewTypeOriginal;

        /* Write out matrix the entries of which are processor indices. */
        if (!MMInsertProcessorIndices(&A)) {
            fprintf(stderr, "main(): Unable to write processor indices!\n");
            exit(-1);
        }
    
        A.MMTypeCode[0] = 'M';
        sprintf(output, "%s-I%d", Options.matrix, A.NrProcs);
    
        File = fopen(output, "w");
    
        if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
        else {
            MMWriteSparseMatrix(&A, File, NULL, &Options);
            fclose(File);
        }
        A.MMTypeCode[0] = 'D';
 
        /* Write out permutations. */
        if (A.col_perm != NULL) {
            sprintf(output, "%s-col%d", Options.matrix, A.NrProcs);
            File = fopen(output, "w");
            if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
            else {
                WriteVector(A.col_perm, 0, NULL, A.n, 0, File, &Options);
               fclose(File);
            }
        }
    
        if (A.row_perm != NULL) {
            sprintf(output, "%s-row%d", Options.matrix, A.NrProcs);
            File = fopen(output, "w");
            if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
            else {
                WriteVector(A.row_perm, 0, NULL, A.m, 0, File, &Options);
                fclose(File);
            }
        }

        /* Free local to global index */
        for( i=0; i<A.NrProcs+1; i++ ) {
            free( row_perms[i] );
            free( col_perms[i] );
        }
        free( row_perms ); free( col_perms );
    } else if (Options.OutputMode == OneFile) {
        /* Extended MatrixMarket output */
        if (Options.OutputFormat != OutputEMM) {
            fprintf(stderr, "main(): Single-file output requires EMM format!\n");
            fprintf(stderr, "        overriding output format to EMM.\n");
            Options.OutputFormat = OutputEMM;
        }
        sprintf(EMMcomment, "%% File generated by running Mondriaan on A=%s with p=%d and \\epsilon=%f\n", Options.matrix, A.NrProcs, Options.eps);
        sprintf(EMMcomment, "%s%% Main matrix corresponds to the distributed version of A\n", EMMcomment);
        if (A.row_perm_inv != NULL && A.col_perm_inv != NULL) {
            switch( Options.OrderPermutation ) {
                case OrderPrefix:
                    sprintf(EMMcomment, "%s%% This is followed by the (not-distributed) reverse Bordered Block Diagonal permuted matrix 'PAQ',\n", EMMcomment);
                    break;
                case OrderPostfix:
                    sprintf(EMMcomment, "%s%% This is followed by the (not-distributed) Bordered Block Diagonal permuted matrix 'PAQ',\n", EMMcomment);
                    break;
                default:
                    sprintf(EMMcomment, "%s%% This is followed by the (not-distributed) Separated Block Diagonal permuted matrix 'PAQ',\n", EMMcomment);
            }
            sprintf(EMMcomment, "%s%% followed by the row-block boundary vector 'Row-boundaries',\n", EMMcomment);
            sprintf(EMMcomment, "%s%% followed by the row-block hierarchy vector 'Row-hierarchy',\n", EMMcomment);
            sprintf(EMMcomment, "%s%% followed by the column-block boundary vector 'Column-boundaries',\n", EMMcomment);
            sprintf(EMMcomment, "%s%% followed by the column-block hierarchy vector 'Column-hierarchy',\n", EMMcomment);
        }
        sprintf(EMMcomment, "%s%% followed by a local view of the distributed form of A 'Local-A',\n", EMMcomment);
        sprintf(EMMcomment, "%s%% followed by a mapping of local row indices to global row indices 'LocalRow2Global',\n", EMMcomment);
        sprintf(EMMcomment, "%s%% followed by a mapping of local column indices to global column indices 'LocalCol2Global',\n", EMMcomment);
        if (A.row_perm != NULL)
            sprintf(EMMcomment, "%s%% followed by the row permutation vector corresponding to P in PAQ 'Row-permutation',\n", EMMcomment);
        if (A.col_perm != NULL)
            sprintf(EMMcomment, "%s%% followed by the column permutation vector corresponding to Q in PAQ 'Column-permutation',\n", EMMcomment);
        sprintf(EMMcomment, "%s%% followed by the input vector distribution 'Input-vector',\n", EMMcomment);
        sprintf(EMMcomment, "%s%% followed by the output vector distribution 'Output-vector',\n", EMMcomment);
        sprintf(EMMcomment, "%s%% followed by the local lengths of the output vectors 'OutputVectorLengths',\n", EMMcomment);
        sprintf(EMMcomment, "%s%% followed by the matrix row index to output vector processor ID mapping 'LocalRow2Processor',\n", EMMcomment);
        sprintf(EMMcomment, "%s%% followed by the matrix row index to output vector index mapping 'LocalRow2Index',\n", EMMcomment);
        sprintf(EMMcomment, "%s%% followed by the matrix column index to input vector processor ID mapping 'LocalCol2Processor',\n", EMMcomment);
        sprintf(EMMcomment, "%s%% followed by the matrix column index to input vector index mapping 'LocalCol2Index'.\n", EMMcomment);
        A.comment = EMMcomment;
        sprintf(output, "%s-P%d.emm", Options.matrix, A.NrProcs);
        File = fopen(output, "w");
        if (!File) {
            fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
            exit( -1 );
        }
        MMWriteSparseMatrix(&A, File, NULL, &Options);

        /* Commit to permutation */
        if (A.row_perm_inv != NULL && A.col_perm_inv != NULL) {
            for( i=0; i<A.NrNzElts; i++ ) {
                A.i[ i ] = A.row_perm_inv[ A.i[ i ] ];
                A.j[ i ] = A.col_perm_inv[ A.j[ i ] ];
            }
        }
 
        /* Write permuted matrix */
        A.MMTypeCode[0] = 'M';
        MMWriteSparseMatrix(&A, File, "PAQ", &Options);
        A.MMTypeCode[0] = 'D';

        /* Write out block information */
        if (A.rowBoundaries) {
            if (remembrance_get( A.rowBoundaries )==NULL) {
                fprintf(stderr, "main(): Error during read-out of row boundaries\n");
                exit( -1 );
            }
            temp = malloc(A.rowBoundaries->size * sizeof( long int ));
            for(ui=0; ui<A.rowBoundaries->size; ui++)
                temp[ ui ] = A.rowBoundaries->vector[ ui ].index;
            WriteVector(temp, 0, "Row-boundaries", A.rowBoundaries->size, 0, File, &Options);
            for(ui=0; ui<A.rowBoundaries->size-1; ui++ )
                temp[ ui ] = A.rowBoundaries->vector[ ui ].parent == ULONG_MAX ? 0 : A.rowBoundaries->vector[ ui ].parent + 1;
            WriteVector(temp, 1, "Row-hierarchy", A.rowBoundaries->size-1, 0, File, &Options);
            free(temp);
        }
        if (Options.SplitStrategy != SFineGrain) {
            if (A.colBoundaries) {
                if (remembrance_get( A.colBoundaries )==NULL) {
                    fprintf(stderr, "main(): Error during read-out of column boundaries\n");
                    exit( -1 );
                }
                temp = malloc( A.colBoundaries->size * sizeof( long int ) );
                for(ui=0; ui<A.colBoundaries->size; ui++)
                    temp[ ui ] = A.colBoundaries->vector[ ui ].index;
                WriteVector(temp, 0, "Col-boundaries", A.colBoundaries->size, 0, File, &Options);
                for(ui=0; ui<A.colBoundaries->size-1; ui++ )
                    temp[ ui ] = A.colBoundaries->vector[ ui ].parent == ULONG_MAX ? 0 : A.colBoundaries->vector[ ui ].parent + 1;
                WriteVector(temp, 1, "Col-hierarchy", A.colBoundaries->size-1, 0, File, &Options);
                free(temp);
            }
        }
    
        /* Write out local matrix format */
        row_perms = malloc( (A.NrProcs+1) * sizeof( long int * ) );
        col_perms = malloc( (A.NrProcs+1) * sizeof( long int * ) );
        if( !row_perms || !col_perms || 
            !SparseMatrixOriginal2Local(&A, row_perms, col_perms) ) {
            fprintf(stderr, "main(): Unable to transform to local view!");
            exit(-1);
        }
        MMWriteSparseMatrix(&A, File, "Local-A", &Options);

        /* Transform matrix back from Local to global view */
        for( i=0; i<A.NrProcs; i++ )
            for(j=A.Pstart[i]; j<A.Pstart[i+1]; j++ ) {
                A.i[j] = row_perms[i][ A.i[j] ];
                A.j[j] = col_perms[i][ A.j[j] ];
            }
        A.ViewType = ViewTypeOriginal;

        /* Permutate row_perms and col_perms so that they point
         * to global indices (corresponding to A) instead of
         * permuted indices (corresponding to PAQ). 
        for( i=0; i<A.NrProcs; i++ ) {
                for( j=0; j<row_perms[A.NrProcs][i]; j++ )
                        row_perms[i][j] = row_perms[i][j]; 
                for( j=0; j<col_perms[A.NrProcs][i]; j++ )
                        col_perms[i][j] = col_perms[i][j];
        } */

        WriteVectorCollection(row_perms, "LocalRow2Global", A.NrProcs, row_perms[A.NrProcs], File);
        WriteVectorCollection(col_perms, "LocalCol2Global", A.NrProcs, col_perms[A.NrProcs], File);

        /* Write out matrix the entries of which are processor indices */
        /*if (!MMInsertProcessorIndices(&A)) {
            fprintf(stderr, "main(): Unable to write processor indices!\n");
            exit(-1);
        }
        A.MMTypeCode[0] = 'M';
        tempchar = A.MMTypeCode[2];
        A.MMTypeCode[2] = 'I';
        MMWriteSparseMatrix(&A, File, "Global-A", &Options);
        A.MMTypeCode[0] = 'D';
        A.MMTypeCode[2] = tempchar;*/
 
        /* Write out permutations */
        if (A.row_perm != NULL) {
            WriteVector(A.row_perm, 0, "Row-permutation", A.m, 0, File, &Options);
        }
        if (A.col_perm != NULL) {
            WriteVector(A.col_perm, 0, "Column-permutation", A.n, 0, File, &Options);
        }
    } else if (Options.OutputMode == DIMACS) {
        /* For DIMACS we only need the vector distribution. */
    } else {
        fprintf(stderr, "main(): Unknown output mode!\n" );
        exit( -1 );
    }

    /* Convert symmetrically partitioned, symmetric matrix to full form 
       for vector distribution */
    if (symmetric &&
         Options.SymmetricMatrix_UseSingleEntry == SingleEntYes) {
        /* Some of the above transformations can make A arbitrary symmetric
           instead of lower-traingular */
        SparseMatrixSymmetricRandom2Lower(&A);
        SparseMatrixSymmetric2Full(&A); /* now A.MMTypeCode[3]='G' */
        
        /* Print information about the number of matrix elements */
        AvgNrNzElts = (double) A.NrNzElts / A.NrProcs;
        MinNrNzElts = LONG_MAX;
        MaxNrNzElts = LONG_MIN;
        for (q = 0; q < A.NrProcs; q++) {
             nzq = A.Pstart[q+1] - A.Pstart[q];
             if (nzq < MinNrNzElts)
                 MinNrNzElts = nzq;
             if (nzq > MaxNrNzElts)
                 MaxNrNzElts = nzq;
        }

#ifdef INFO
        printf("  After conversion of distributed symmetric matrix to"
               "  distributed full matrix\n");
        printf("  Nr matrix elements:\n");
        printf("    tot         : %ld \n", A.NrNzElts);
        printf("    avg = tot/P : %g  \n", AvgNrNzElts);
        printf("    max         : %ld \n", MaxNrNzElts);
        printf("    min         : %ld \n", MinNrNzElts);

        printf("    imbalance   : %g %c\n", 
                    100 * (MaxNrNzElts / AvgNrNzElts - 1.0), '%');
        /* vertex weight information is not printed, since it is not
           meaningful here */ 
#endif   
    }
  
#ifdef INFO
    printf("\n****** Mondriaan vector distribution ******\n");
#endif
  
    /* Allocate memory for processor numbers for the vector components, 
       for u = A*v with A an m by n matrix */
    u_proc = (long int *) malloc(A.m * sizeof(long int));
    v_proc = (long int *) malloc(A.n * sizeof(long int));
    if (u_proc == NULL || v_proc == NULL) {
        fprintf(stderr, "main(): Not enough memory for vectors u_proc and v_proc!\n");
        exit(-1);
    }
      
    /**** Distribute the vector (and time it) ****/
    starttime = clock();
#ifdef UNIX
    gettimeofday(&starttime1, NULL);
#endif
   
    if (A.m == A.n && Options.SquareMatrix_DistributeVectorsEqual == EqVecYes) {
        /* Distribute the vectors equally */
        if (symmetric &&
             Options.SymmetricMatrix_UseSingleEntry == SingleEntYes) {
             
            /* Distribute v independently, and then use the same distribution for u */
            ComV = DistributeVec(&A, v_proc, ROW, &Options);
            
            if (ComV < 0) {
                fprintf(stderr, "main(): Unable to distribute vectors!\n");
                exit(-1);
            }
            
            for (i = 0; i < A.m; i++)
                u_proc[i] = v_proc[i];
            ComU = ComV;
#ifdef INFO
            printf("\nCommunication results for u are the same as for v\n");
            printf("but with sends and receives reversed\n\n");
#endif
        } else {
            /* Distribute u and v together */
            ComU = DistributeVecOrigEq(&A, u_proc, v_proc, &Options);
            
            if (ComU < 0) {
                fprintf(stderr, "main(): Unable to distribute vectors!\n");
                exit(-1);
            }
            
            ComV = 0;
        }
    } else {
        /* Distribute the vectors independently */
        ComV = DistributeVec(&A, v_proc, ROW, &Options);
        if (ComV < 0) {
            fprintf(stderr, "main(): Unable to distribute input vector!\n");
            exit(-1);
        }

        ComU = DistributeVec(&A, u_proc, COL, &Options);
        if (ComU < 0) {
            fprintf(stderr, "main(): Unable to distribute output vector!\n");
            exit(-1);
        }
    }
  
    endtime = clock();
#ifdef UNIX
    gettimeofday(&endtime1, NULL);
#endif
    cputime = ((double) (endtime - starttime)) / CLOCKS_PER_SEC;
  
#ifdef TIME
    printf("  vector distribution CPU-time      : %f seconds\n", cputime);
#ifdef UNIX  
    printf("  vector distribution elapsed time  : %f seconds\n",
             (endtime1.tv_sec - starttime1.tv_sec) +
             (endtime1.tv_usec - starttime1.tv_usec) / 1000000.0); 
#endif   
    fflush(stdout);
#endif  
      
#ifdef INFO
    printf("\nCommunication cost for u = A v: %ld (%g) \n", ComU + ComV,
           ((double) ComU / A.m  + (double) ComV / A.n) /2);  
    fflush(stdout);
#endif
 
    /* Write vector info */
    if (Options.OutputMode == MultipleFiles) {
        /* Write the vector distribution to file */
        sprintf(output, "%s-u%d", Options.matrix, A.NrProcs);
        File = fopen(output, "w");
    
        if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
        else {
            WriteVectorDistribution(u_proc, NULL, A.m, A.NrProcs, File, &Options);
            fclose(File);
        }
  
        sprintf(output, "%s-v%d", Options.matrix, A.NrProcs);    
        File = fopen(output, "w");
    
        if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
        else {
            WriteVectorDistribution(v_proc, NULL, A.n, A.NrProcs, File, &Options);
            fclose(File);
        }
    } else if (Options.OutputMode == OneFile) {
        /* Write the vector distribution to file */
        WriteVectorDistribution(v_proc, "Input-vector", A.n, A.NrProcs, File, &Options);
        WriteVectorDistribution(u_proc, "Output-vector", A.m, A.NrProcs, File, &Options);

        /* LocalRow2Processor */
        inv_count = NULL;
        row_local2proc = row_local2index = col_local2proc = col_local2index = NULL;
       if(!SparseMatrixLocal2Vector(&A, row_perms, u_proc, &inv_count, &row_local2proc, &row_local2index, 0)) {
            fprintf(stderr, "Error during derivation of local index arrays for SpMV multiplication (row direction)\n");
            exit(-1);
        }
        WriteVector(inv_count, 0, "OutputVectorLengths", A.NrProcs, 0, File, &Options);
        WriteVectorCollection(row_local2proc, "LocalRow2Processor", A.NrProcs, row_perms[A.NrProcs], File);
        WriteVectorCollection(row_local2index, "LocalRow2Index", A.NrProcs, row_perms[A.NrProcs], File);
        for( i=0; i<A.NrProcs; i++ ) {
            free( row_local2proc[i] );
            free( row_local2index[i] );
        }
        free( row_local2proc ); free( row_local2index );
        /* LocalCol2Processor */
        free(inv_count);
       if(!SparseMatrixLocal2Vector(&A, col_perms, v_proc, &inv_count, &col_local2proc, &col_local2index, 1)) {
            fprintf(stderr, "Error during derivation of local index arrays for SpMV multiplication (column direction)\n");
            exit(-1);
        }
        WriteVector(inv_count, 0, "InputVectorLengths", A.NrProcs, 0, File, &Options);
        WriteVectorCollection(col_local2proc, "LocalCol2Processor", A.NrProcs, col_perms[A.NrProcs], File);
        WriteVectorCollection(col_local2index, "LocalCol2Index", A.NrProcs, col_perms[A.NrProcs], File);
        for( i=0; i<A.NrProcs; i++ ) {
            free( col_local2proc[i] );
            free( col_local2index[i] );
        }
        free( col_local2proc ); free( col_local2index );
        free(inv_count);
        /* Also free local to global index */
        for( i=0; i<A.NrProcs+1; i++ ) {
            free( row_perms[i] );
            free( col_perms[i] );
        }
        free( row_perms ); free( col_perms );
        fclose(File);
    } else if (Options.OutputMode == DIMACS) {
        if (A.m != A.n || Options.SquareMatrix_DistributeVectorsEqual != EqVecYes) {
            fprintf(stderr, "main(): Unequal vector distributions in DIMACS mode!\n");
        }
        
        /* Only write the vector distribution to disk. */
        sprintf(output, "%s%d.part", Options.matrix, A.NrProcs);
        File = fopen(output, "w");
    
        if (!File) {
            fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
        } else {
            for (i = 0; i < A.m; i++) fprintf(File, "%ld\n", u_proc[i]);
            fclose(File);
        }
    }
  
    if (Options.OutputMode == MultipleFiles) {
        /* Write the index sets of the Cartesian submatrices to file */
        sprintf(output, "%s-C%d", Options.matrix, A.NrProcs);
        File = fopen(output, "w");
        if (!File) fprintf(stderr, "main(): Unable to open '%s' for writing!\n", output);
        else {
            MMWriteCartesianSubmatrices(&A, File);
            fclose(File);
        }
    }

    /* Free memory */
    MMDeleteSparseMatrix(&A);  
    free(v_proc);
    free(u_proc);

    /* Exit :) */
    exit(0);
    
} /* end main */
Beispiel #20
0
bool CGraphmatFile :: GraphmatMain ()
{
    m_LastError = "";

    if (0x500000 < GetInputBuffer().size())
    {
        m_LastError = "File is to large, it cannot be more than 5 MB";
        return false;
    };


    InitTokenBuffer();

    {
        // NUMBER of all UNITS which were read from INPUT file
        size_t  CurrOutBufOffset  = 0;

        // we should process all bytes except the last terminating null
        size_t InputBufferSize = GetInputBuffer().size()-1;

        for (size_t InputOffset  = 0; InputOffset < InputBufferSize ; )
        {
            CGraLine NewLine;

            NewLine.SetToken(GetUnitBufferStart() + CurrOutBufOffset);
            DWORD	PageNumber;
            InputOffset = NewLine.ReadWord(InputOffset,this, PageNumber);

            //  ignore single spaces in order to save memory
            if	( !NewLine.IsSingleSpaceToDelete() )
            {
                AddUnit(NewLine);
                CurrOutBufOffset += NewLine.GetTokenLength();
                if (NewLine.IsPageBreak() )
                    SetPageNumber(GetUnits().size() - 1,PageNumber);
            }
            else
            {
                assert (!GetUnits().empty());
                GetUnit(GetUnits().size() -1).SetSingleSpaceAfter();
            };


        }
    }


    // больше TBuf не нужен, так что освобождаем память
    ClearInputBuffer();


    for (size_t i=1; i< GetUnits().size(); i++)
        InitNonContextDescriptors(GetUnit(i));


    if (m_bOnlyNonContextDescriptors)
        return true;

    BuildUnitBufferUpper();

    InitContextDescriptors (0,GetUnits().size());

    MacSynHierarchy();


    if (m_bSentBreaker)
        if (!DealSentBreaker ())
        {
            m_LastError = "An exception occurred in Sentence breaker";
            return false;
        };


    if   (m_bWriteTextBuffer)
        WriteVector(m_SaveTxtName, GetUnitBuf());

    if   (m_bWriteGraFile)
        WriteGraphMat (m_GraFileName.c_str());


    return true;
};
Beispiel #21
0
int _tmain(int argc, _TCHAR* argv[])
{
	int t=2,conv,num_class_1=0,num_class_2=0,num_class_3=0,num_class_4=0,num_class_5=0;
	double c,g,a,am=0,cs,gs;
	char input[100]="", wn[100], dn[100], filebase[100]="";
	std::ifstream tmp;
	//_crtBreakAlloc = 6000;
	//_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
	int q='w',lbl=-1;
	IplImage *frame;
	cvNamedWindow(ONE,1);
	cvNamedWindow(TWO,1);
	std::ofstream output("output-svm-format.data.txt");
	cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 2.0, 2.0, 0, 2, CV_AA);
#ifdef CAMERA
	Capture* cam=new Capture();
#else
	Capture* cam=new Capture(FILENAME);
#endif

#ifdef AAM_TRACK
	AAM_Pyramid model;
	model.ReadModel("D:\\Documents and Settings\\sreedalm\\My Documents\\AAM\\AAMLib-GSOC\\example\\my.amf");
	VJfacedetect facedet;
	facedet.LoadCascade("C:/Program Files/OpenCV/data/haarcascades/haarcascade_frontalface_default.xml");//D:/Documents and Settings/sreedalm/My Documents/AAM/AAMLib-GSOC2/example/haarcascade_frontalface_alt2.xml");
	AAM_Shape Shape;
	bool started=false;
#endif
#ifndef __DEBUG__
	Detector* faceDetector=new Detector(/*"C:/Program Files/OpenCV/data/haarcascades/*/"haarcascade_frontalface_default.xml");
	faceDetector->setMinSize(cam->getNextFrame(GC_BGR)->width/5);
	Detector* noseDetector=new Detector(/*"C:/Program Files/OpenCV/data/haarcascades/*/"Nose1.xml");
	noseDetector->setMinSize(25,15);
	Detector* mouthDetector=new Detector(/*"C:/Program Files/OpenCV/data/haarcascades/*/"Mouth.xml");
	mouthDetector->setMinSize(25,15);
	Detector* eyeRegionDetector=new Detector(/*"C:/Program Files/OpenCV/data/haarcascades/*/"frontalEyes35x16.xml");
	eyeRegionDetector->setMinSize(25,15);
	Detector* eyeDetector=new Detector(/*"C:/Program Files/OpenCV/data/haarcascades/*/"ojoD.xml");
	Blink* blinkEyeDetector=new Blink();
	SuperTracker* trackAll=new SuperTracker(eyeDetector,eyeRegionDetector,noseDetector,mouthDetector,faceDetector);
	Classifier *svm_nod=new Classifier(/*"D:\\Documents and Settings\\sreedalm\\My Documents\\Organised\\Permanent\\Work\\Libraries\\ML\\Classifiers\\SVM\\libsvm-2.89\\windows\\svm-nod-detect\\*/"model.nod.061009"/*out*/,/*"D:\\Documents and Settings\\sreedalm\\My Documents\\Organised\\Permanent\\Work\\Libraries\\ML\\Classifiers\\SVM\\libsvm-2.89\\windows\\*/"nod-scale-info.txt");
	Classifier *svm_shake=new Classifier(/*"D:\\Documents and Settings\\sreedalm\\My Documents\\Organised\\Permanent\\Work\\Libraries\\ML\\Classifiers\\SVM\\libsvm-2.89\\windows\\svm-shake-detect\\*/"model.shake.061009"/*data*/,/*"D:\\Documents and Settings\\sreedalm\\My Documents\\Organised\\Permanent\\Work\\Libraries\\ML\\Classifiers\\SVM\\libsvm-2.89\\windows\\*/"shake-scale-info.txt");
	Classifier *extra_class=NULL;
#else
	Detector* faceDetector=new Detector("C:/Program Files/OpenCV/data/haarcascades/haarcascade_frontalface_default.xml");
	faceDetector->setMinSize(cam->getNextFrame(GC_BGR)->width/5);
	Detector* noseDetector=new Detector("C:/Program Files/OpenCV/data/haarcascades/Nose1.xml");
	noseDetector->setMinSize(25,15);
	Detector* mouthDetector=new Detector("C:/Program Files/OpenCV/data/haarcascades/Mouth.xml");
	mouthDetector->setMinSize(25,15);
	Detector* eyeRegionDetector=new Detector("C:/Program Files/OpenCV/data/haarcascades/frontalEyes35x16.xml");
	eyeRegionDetector->setMinSize(25,15);
	Detector* eyeDetector=new Detector("C:/Program Files/OpenCV/data/haarcascades/ojoD.xml");
	Blink* blinkEyeDetector=new Blink();
	SuperTracker* trackAll=new SuperTracker(eyeDetector,eyeRegionDetector,noseDetector,mouthDetector,faceDetector);
	Classifier *svm_nod=new Classifier("D:\\Documents and Settings\\sreedalm\\My Documents\\Organised\\Permanent\\Work\\Libraries\\ML\\Classifiers\\SVM\\libsvm-2.89\\windows\\svm-nod-detect\\model.nod.061009"/*out*/,"D:\\Documents and Settings\\sreedalm\\My Documents\\Organised\\Permanent\\Work\\Libraries\\ML\\Classifiers\\SVM\\libsvm-2.89\\windows\\svm-nod-detect\\scale-info.txt");
	Classifier *svm_shake=new Classifier("D:\\Documents and Settings\\sreedalm\\My Documents\\Organised\\Permanent\\Work\\Libraries\\ML\\Classifiers\\SVM\\libsvm-2.89\\windows\\svm-shake-detect\\model.shake.061009"/*data*/,"D:\\Documents and Settings\\sreedalm\\My Documents\\Organised\\Permanent\\Work\\Libraries\\ML\\Classifiers\\SVM\\libsvm-2.89\\windows\\svm-shake-detect\\scale-info.txt");
	Classifier *extra_class=NULL;
#endif
	for(int i=0;i<10;i++) frame=cam->getNextFrame(GC_BGR);
	while(1){
		frame=cam->getNextFrame(GC_BGR);
		if(frame==NULL) break;
		trackAll->nextStep(frame);
#ifdef AAM_TRACK
		if(trackAll->isDetected() && faceDetector->getIthDetection(1)){ started=model.InitShapeFromDetBox(Shape, facedet, frame);}
		if(started && faceDetector->getIthDetection(1)) model.Fit(frame, Shape, 25, false);
#endif
		frame=trackAll->drawStep();
		
#ifdef AAM_TRACK
		if(started && faceDetector->getIthDetection(1)) model.Draw(frame, Shape, 1);
#endif
		cvShowImage(ONE,frame);
		//q='w';
		//q=cvWaitKey(1);
		if(q==27) break;
		if(q=='n') 
			lbl=-1;//WriteVector(trackAll->getTrack(GC_NOSE),30,output,-1);
		if(q=='p') 
			lbl=1;//WriteVector(trackAll->getTrack(GC_NOSE),30,output,1);
		if(q=='c') 
			if(t==2) 
				t=0; 
			else 
				t=2;
		{
			char temp[100]="";
			if(q=='1'){
				printf("Writing images for class 1\n");
				strcpy(filebase,CLASS_1);
				itoa(num_class_1++,temp,10);
				strcat(filebase,temp);
			}
			else if(q=='2'){
				printf("Writing images for class 2\n");
				strcpy(filebase,CLASS_2);
				itoa(num_class_2++,temp,10);
				strcat(filebase,temp);
			}
			else if(q=='3'){
				printf("Writing images for class 3\n");
				strcpy(filebase,CLASS_3);
				itoa(num_class_3++,temp,10);
				strcat(filebase,temp);
			}
			else if(q=='4'){
				printf("Writing images for class 4\n");
				strcpy(filebase,CLASS_4);
				itoa(num_class_4++,temp,10);
				strcat(filebase,temp);
			}
			else {
				printf("Writing images for class 5\n");
				strcpy(filebase,CLASS_5);
				itoa(num_class_5++,temp,10);
				strcat(filebase,temp);
			}
			trackAll->writeImages(filebase);
		}
#ifdef AUTO_TRAIN
		if(q=='t')
		{
			t=0;
			output.close();
			system("svm-scale.exe -s tmp.scale output-svm-format.data.txt > scaled.input.data");
			system("grid.py -log2c -2,2,1 -log2g -2,2,1 -svmtrain svm-train.exe -gnuplot pgnuplot.exe -s 0 -t 2 scaled.input.data");
			tmp.open("scaled.input.data.out");
			while(!tmp.fail()){
				if(a>am && c!=0){
					cs=c;
					gs=g;
					am=a;
				}
				tmp>>c>>g>>a;
				printf("%lf:%lf:%lf:->:%lf:%lf:%lf\n",c,g,a,cs,gs,am);
			}
			strcpy(input,"svm-train.exe -s 0 -t 2 -c \0");
			itoa((int)cs,wn,10);
			itoa((int)((cs-(int)cs)*1000),dn,10);
			strcat(input,wn);
			strcat(input,".\0");
			strcat(input,dn);
			strcat(input," -g \0");
			itoa((int)gs,wn,10);
			itoa((int)((gs-(int)gs)*1000),dn,10);
			strcat(input,wn);
			strcat(input,".\0");
			strcat(input,dn);
			strcat(input," scaled.input.data model.extra_class\0\n");
			printf("%s\n",input);
			getchar();
			system(input);
			if(extra_class) delete extra_class; 
			extra_class=new Classifier("model.extra_class","tmp.scale");
			output.open("output-svm-format.data.txt",std::ios_base::app);
		}
#endif
		if(trackAll->getTrack(GC_NOSE).size()>FEATURE_SIZE){
#ifdef MAIN_TRACKING
			frame=DetectFacialGestures(trackAll->getTrack(GC_NOSE),svm_nod,svm_shake,extra_class,frame);
#endif
#ifdef AUTO_TRAIN
			WriteVector(trackAll->getTrack(GC_NOSE),FEATURE_SIZE,output,lbl);
#endif
		}
		cvShowImage(TWO,frame);
		q=cvWaitKey(t);
		cvReleaseImage(&frame);
	}
Beispiel #22
0
bool CSave::WriteFields( const char *pname, void *pBaseData, const DataMap_t& dataMap, const TYPEDESCRIPTION *pFields, int fieldCount )
{
	int				i, j;
	const TYPEDESCRIPTION	*pTest;
	int				entityArray[ MAX_ENTITYARRAY ];

	// Precalculate the number of empty fields
	int actualCount = 0;
	for( i = 0; i < fieldCount; i++ )
	{
		pTest = &pFields[ i ];
		void *pOutputData;
		pOutputData = ( ( char * ) pBaseData + pTest->fieldOffset );
		if( ( pTest->flags & TypeDescFlag::SAVE ) && !DataEmpty( ( const char * ) pOutputData, pTest->fieldSize * g_SaveRestoreSizes[ pTest->fieldType ] ) )
			++actualCount;
	}

	// Empty fields will not be written, write out the actual number of fields to be written
	WriteInt( pname, &actualCount, 1 );

	for( i = 0; i < fieldCount; i++ )
	{
		void *pOutputData;
		pTest = &pFields[ i ];
		pOutputData = ( ( char * ) pBaseData + pTest->fieldOffset );

		// UNDONE: Must we do this twice?
		//TODO: update CSaveRestoreBuffer to allow seeking to write to earlier locations. - Solokiller
		if( !( pTest->flags & TypeDescFlag::SAVE ) || DataEmpty( ( const char * ) pOutputData, pTest->fieldSize * g_SaveRestoreSizes[ pTest->fieldType ] ) )
			continue;

		switch( pTest->fieldType )
		{
		case FIELD_FLOAT:
			WriteFloat( pTest->fieldName, ( float * ) pOutputData, pTest->fieldSize );
			break;
		case FIELD_TIME:
			WriteTime( pTest->fieldName, ( float * ) pOutputData, pTest->fieldSize );
			break;
		case FIELD_MODELNAME:
		case FIELD_SOUNDNAME:
		case FIELD_STRING:
			WriteString( pTest->fieldName, ( int * ) pOutputData, pTest->fieldSize );
			break;
		case FIELD_CLASSPTR:
		case FIELD_EVARS:
		case FIELD_EDICT:
		case FIELD_ENTITY:
		case FIELD_EHANDLE:
			if( pTest->fieldSize > MAX_ENTITYARRAY )
				ALERT( at_error, "Can't save more than %d entities in an array!!!\n", MAX_ENTITYARRAY );
			for( j = 0; j < pTest->fieldSize; j++ )
			{
				switch( pTest->fieldType )
				{
				case FIELD_EVARS:
					entityArray[ j ] = EntityIndex( ( ( entvars_t ** ) pOutputData )[ j ] );
					break;
				case FIELD_CLASSPTR:
					entityArray[ j ] = EntityIndex( ( ( CBaseEntity ** ) pOutputData )[ j ] );
					break;
				case FIELD_EDICT:
					entityArray[ j ] = EntityIndex( ( ( edict_t ** ) pOutputData )[ j ] );
					break;
				case FIELD_ENTITY:
					entityArray[ j ] = EntityIndex( ( ( EOFFSET * ) pOutputData )[ j ] );
					break;
				case FIELD_EHANDLE:
					entityArray[ j ] = EntityIndex( ( CBaseEntity * ) ( ( ( EHANDLE * ) pOutputData )[ j ] ) );
					break;
				}
			}
			WriteInt( pTest->fieldName, entityArray, pTest->fieldSize );
			break;
		case FIELD_POSITION_VECTOR:
			WritePositionVector( pTest->fieldName, ( float * ) pOutputData, pTest->fieldSize );
			break;
		case FIELD_VECTOR:
			WriteVector( pTest->fieldName, ( float * ) pOutputData, pTest->fieldSize );
			break;

		case FIELD_BOOLEAN:
			//TODO: should be written as a bit perhaps? - Solokiller
			WriteBoolean( pTest->fieldName, ( bool* ) pOutputData, pTest->fieldSize );
			break;

		case FIELD_INTEGER:
			WriteInt( pTest->fieldName, ( int * ) pOutputData, pTest->fieldSize );
			break;

		case FIELD_SHORT:
			WriteData( pTest->fieldName, 2 * pTest->fieldSize, ( ( char * ) pOutputData ) );
			break;

		case FIELD_CHARACTER:
			WriteData( pTest->fieldName, pTest->fieldSize, ( ( char * ) pOutputData ) );
			break;

		case FIELD_FUNCPTR:
			WriteFunction( pTest->fieldName, ( void ** ) pOutputData, pTest->fieldSize, dataMap, *pTest );
			break;
		default:
			ALERT( at_error, "Bad field type\n" );
		}
	}

	return true;
}
Beispiel #23
0
void CFile::WriteMatrix (const CFixMatrix& m)
{
WriteVector (m.RVec());
WriteVector (m.UVec());
WriteVector (m.FVec());
}
Beispiel #24
0
void CSave::WriteVector( const char *pname, const Vector &value )
{
	WriteVector( pname, &value.x, 1 );
}
Beispiel #25
0
inline std::size_t
  WriteJump(Process const& process,
            void* address,
            void* target,
            bool push_ret_fallback,
            std::vector<std::unique_ptr<Allocator>>* trampolines)
{
  HADESMEM_DETAIL_TRACE_FORMAT_A(
    "Address = %p, Target = %p, Push Ret Fallback = %u.",
    address,
    target,
    static_cast<std::uint32_t>(push_ret_fallback));

  std::vector<std::uint8_t> jump_buf;

#if defined(HADESMEM_DETAIL_ARCH_X64)
  if (IsNear(address, target))
  {
    HADESMEM_DETAIL_TRACE_A("Using relative jump.");
    jump_buf = GenJmp32(address, target);
    HADESMEM_DETAIL_ASSERT(jump_buf.size() == PatchConstants::kJmpSize32);
  }
  else
  {
    std::unique_ptr<Allocator> trampoline;

    if (trampolines)
    {
      try
      {
        trampoline = AllocatePageNear(process, address);
      }
      catch (std::exception const& /*e*/)
      {
        // Don't need to do anything, we'll fall back to PUSH/RET.
      }
    }

    if (trampoline)
    {
      void* tramp_addr = trampoline->GetBase();

      HADESMEM_DETAIL_TRACE_FORMAT_A("Using trampoline jump. Trampoline = %p.",
                                     tramp_addr);

      Write(process, tramp_addr, target);

      trampolines->emplace_back(std::move(trampoline));

      jump_buf = GenJmpTramp64(address, tramp_addr);
      HADESMEM_DETAIL_ASSERT(jump_buf.size() == PatchConstants::kJmpSize64);
    }
    else
    {
      if (!push_ret_fallback)
      {
        // We're out of options...
        HADESMEM_DETAIL_THROW_EXCEPTION(
          Error{} << ErrorString{"Unable to use a relative or trampoline "
                                 "jump, and push/ret fallback is disabled."});
      }

      HADESMEM_DETAIL_TRACE_A("Using push/ret 'jump'.");

      auto const target_high = static_cast<std::uint32_t>(
        (reinterpret_cast<std::uintptr_t>(target) >> 32) & 0xFFFFFFFF);
      if (target_high)
      {
        HADESMEM_DETAIL_TRACE_A("Push/ret 'jump' is big.");
        jump_buf = GenPush64Ret(target);
        HADESMEM_DETAIL_ASSERT(jump_buf.size() ==
                               PatchConstants::kPushRetSize64);
      }
      else
      {
        HADESMEM_DETAIL_TRACE_A("Push/ret 'jump' is small.");
        jump_buf = GenPush32Ret(target);
        HADESMEM_DETAIL_ASSERT(jump_buf.size() ==
                               PatchConstants::kPushRetSize32);
      }
    }
  }
#elif defined(HADESMEM_DETAIL_ARCH_X86)
  (void)push_ret_fallback;
  (void)trampolines;
  HADESMEM_DETAIL_TRACE_A("Using relative jump.");
  jump_buf = GenJmp32(address, target);
  HADESMEM_DETAIL_ASSERT(jump_buf.size() == PatchConstants::kJmpSize32);
#else
#error "[HadesMem] Unsupported architecture."
#endif

  WriteVector(process, address, jump_buf);

  return jump_buf.size();
}
static void WriteCamera(FILE *f, const camera_params_t &camera)
{
    WriteVector(f, 9, camera.R);
    WriteVector(f, 3, camera.t);
    fprintf(f, "%0.16e\n", camera.f);
}
static void WriteCameraPose(FILE *f, const camera_params_t &camera)
{
    WriteVector(f, 9, camera.R);
    WriteVector(f, 3, camera.t);
}
HRESULT CXMLExporterBase::WriteOption(BSTR name, _variant_t value)
{
    HRESULT hr;
    _bstr_t bName(name, true);
    switch( value.vt )
    {
        case VT_I4:
        case VT_I2:
            Write("<Option name=\"%s\" value=\"%d\" />\n",
                  (const char*)bName, (long)value);
            break;
        case VT_R4:
        case VT_R8:
            Write("<Option name=\"%s\" value=\"%g\" />\n",
                  (const char*)bName, (double)value);
            break;
        case VT_BOOL:
            Write("<Option name=\"%s\" value=\"%s\" />\n",
                  (const char*)bName, BoolToText((bool)value));
            break;
        case VT_BSTR:
        {
            _bstr_t bValue = (_bstr_t) value.bstrVal;
            Write("<Option name=\"%s\" value=\"%s\" />\n",
                (const char*)bName, (const char*)bValue);
        }
            break;
        case VT_DATE:
        {
#ifdef _WIN32
            DATE time = (DATE)value;
            SYSTEMTIME sysTime;
            if( VariantTimeToSystemTime(time, &sysTime) )
            {
                TCHAR dateStr[16], timeStr[16];
                GetDateFormat(NULL, 0, &sysTime, _T("MM'/'dd'/'yyyy"), dateStr, 16);
                GetTimeFormat(NULL, 0, &sysTime, _T("HH':'mm':'ss"), timeStr, 16);
                Write("<Option name=\"%s\" value=\"%s %s\" />\n",
                      (const char*)bName, dateStr, timeStr);
            }
            else
            {
                Write("<Option name=\"%s\" value=\"invalid time\" />\n",
                      (const char*)bName);
            }
#else
            // On the Mac, DATE == time_t
            DATE date = value.date;
            Write("<Option name=\"%s\" value=\"%s\" />\n",
                  (const char*)bName, asctime(gmtime((time_t*)&date)));
#endif
        }
            break;
        case VT_UNKNOWN:
            // The unknown can be either a point or a vector
            {
                IUnknown* pUnk = value.punkVal;
                ISkpPoint3d* pPoint = NULL;
                hr = pUnk->QueryInterface(IID_ISkpPoint3d, (void**)&pPoint);
                if( SUCCEEDED(hr) )
                {
                    double p[3];
                    pPoint->Get(p, p+1, p+2);
                    WritePosition( (const char*)bName , p);
                    RELEASE(pPoint);
                }
                else
                {
                    ISkpVector3d* pVec = NULL;
                    hr = pUnk->QueryInterface(IID_ISkpVector3d, (void**)&pVec);
                    if( SUCCEEDED(hr) )
                    {
                        double v[3];
                        pVec->Get(v,v+1,v+2);
                        WriteVector( (const char*)bName , v);
                        RELEASE(pVec);
                    }
                }
            
            }
            break;
        default:
            Write("<Option name=\"%s\" value=\"unknown type\" />\n", (const char*)bName);
    }

    return S_OK;
}
Beispiel #29
0
void MULTIPLAY::SendState()
{
	//send a state if necessary
	
	float remain;
	int mult;
	mult = (int) ((timeindex[0]+FrameTime()/2.0) / STATE_FREQUENCY);
	remain = (timeindex[0] + FrameTime()/2.0) - (float)(mult * STATE_FREQUENCY);
	
	if (remain < FrameTime())
	{
		if (NET_DEBUG)
		{
			cout << "net:  SendState:  sending state at time " << GetCurState(0)->time << endl;
			cout << "used buffers: " << net.NumBufferedPackets() << endl;
		}
		
		//it's time to record a state
		curstates[0].fnum = fnums[0]; //set the number of funcs
		if (curstates[0].funcmem != NULL) //clear old func data
		{
			delete [] curstates[0].funcmem;
			curstates[0].funcmem = NULL;
		}
		curstates[0].funcmem = new FUNCTION_MEMORY_SYNC [fnums[0]]; //allocate func data
		int i;
		for (i = 0; i < fnums[0]; i++) //record current func data
		{
			curstates[0].funcmem[i].oldval = GetFuncMem(0)[i].oldval;
			curstates[0].funcmem[i].newval = GetFuncMem(0)[i].newval;
			curstates[0].funcmem[i].held = GetFuncMem(0)[i].held;
			curstates[0].funcmem[i].active = GetFuncMem(0)[i].active;
			curstates[0].funcmem[i].lastupdateat = GetFuncMem(0)[i].lastupdateat;
		}
		
		
		//now, send a packet
		Uint8 tp[MAX_PACKET_SIZE];
		int tplen = 0;
		Uint8 tempchar;
		tempchar = replay.Get_FuncStateInfo();
		tplen = AddToData(tp, &tempchar, sizeof(Uint8), tplen);
		tplen = AddToData(tp, &GetCurState(0)->time, sizeof(double), tplen);
		//fwrite(&time, sizeof(double), 1, fout);
		tplen = WriteVector(GetCurState(0)->chassispos, tp, tplen);
		tplen = WriteMatrix(GetCurState(0)->chassisorientation, tp, tplen);
		tplen = WriteVector(GetCurState(0)->chassisvel, tp, tplen);
		tplen = WriteVector(GetCurState(0)->chassisangvel, tp, tplen);
		
		for (i = 0; i < 4; i++)
		{
			tplen = AddToData(tp, &GetCurState(0)->suspdisp[i], sizeof(double), tplen);
			tplen = AddToData(tp, &GetCurState(0)->suspcompvel[i], sizeof(double), tplen);
			tplen = WriteVector(GetCurState(0)->whlangvel[i], tp, tplen);
			tplen = AddToData(tp, &GetCurState(0)->tirespeed[i], sizeof(double), tplen);
		}
		
		tplen = AddToData(tp, &GetCurState(0)->gear, sizeof(int), tplen);
		tplen = AddToData(tp, &GetCurState(0)->enginespeed, sizeof(double), tplen);
		tplen = AddToData(tp, &GetCurState(0)->clutchspeed, sizeof(double), tplen);
		tplen = AddToData(tp, &GetCurState(0)->enginedrag, sizeof(double), tplen);
		
		tplen = AddToData(tp, &GetCurState(0)->segment, sizeof(int), tplen);
		
		//write a function state block
		tplen = AddToData(tp, &(fnums[0]), sizeof(int), tplen);
		
		for (i = 0; i < fnums[0]; i++)
		{
			//fwrite(&(funcmem[i]), sizeof(struct FUNCTION_MEMORY_SYNC), 1, fout);
			tplen = AddToData(tp, &(GetCurState(0)->funcmem[i]), sizeof(struct FUNCTION_MEMORY_SYNC), tplen);
		}
		
		net.Send(tp, tplen);
		
		if (MP_RECORD && !MP_REMOTE_RECORD)
		{
			dbgstate[dbgnumstates].CopyFrom(curstates[0]);
			dbgnumstates++;
		}
	}
	//else cout << timeindex[0] << "," << mult << "," << remain << endl;
}
Beispiel #30
0
int main(int argc, char *argv[])
{
  if (argc < 3)
  {
    printf("Invalid input parameters\n");
    return 1;
  }
  
  int N = atoi(argv[1]);
  int NZ = atoi(argv[2]);
  char *mtxFileName = NULL;
  char *vecFileName = NULL;
  if (argc > 3 && argc < 6)
  {
      mtxFileName = argv[3];
      vecFileName = argv[4];
  }

  if ((NZ > N) || (N <= 0) || (NZ <= 0))
  {
    printf("Incorrect arguments of main\n");
    return 1;
  }

  crsMatrix A;
  double *x, *b, *bm;
  double timeM=0, timeM1=0, diff=0;

  if (ReadMatrix(A, mtxFileName) != 0)
  {
    GenerateRegularCRS(1, N, NZ, A);
    WriteMatrix(A, "mtx.txt");
  }
  if (ReadVector(&x, N, vecFileName) != 0)
  {
    GenerateVector(2, N, &x);
    WriteVector(x, N, "vec.txt");
  }

  InitializeVector(N, &b);
  Multiplicate(A, x, b, timeM);

  InitializeVector(N, &bm);
  SparseMKLMult(A, x, bm, timeM1);

  CompareVectors(b, bm, N, diff);

  if (diff < EPSILON)
    printf("OK\n");
  else
    printf("not OK\n");
  printf("%d %d\n", A.N, A.NZ);
  printf("%.3f %.3f\n", timeM, timeM1);

  FreeMatrix(A);
  FreeVector(&b);
  FreeVector(&bm);
  FreeVector(&x);

  return 0;
}