예제 #1
0
bool ModelParametersGMR::saveGMM(string directory, const vector<VectorXd>& centers, const vector<MatrixXd>& covars, int iter)
{
  for (size_t i_gau = 0; i_gau < centers.size(); i_gau++)
  {
    stringstream stream;
    stream << "gmm";
    if (iter>=0)
      stream << "_iter" << setw(2) << setfill('0') << iter;
    stream  << "_mu" << setw(3) << setfill('0') << i_gau << ".txt";
    string filename = stream.str();
    if (!saveMatrix(directory, filename,  centers[i_gau],  true))
      return false;
    cout << "  filename=" << filename << endl;
    
    stringstream stream2;
    stream2 << "gmm";
    if (iter>=0)
      stream2 << "_iter" << setw(2) << setfill('0') << iter;
    stream2  << "_covar" << setw(3) << setfill('0') << i_gau << ".txt";
    filename = stream2.str();
    cout << "  filename=" << filename << endl;
    if (!saveMatrix(directory, filename,  covars[i_gau],  true))
      return false;    
  }
  return true;
}
예제 #2
0
bool FunctionApproximatorGPR::saveGridData(const VectorXd& min, const VectorXd& max, const VectorXi& n_samples_per_dim, string save_directory, bool overwrite) const
{
  if (save_directory.empty())
    return true;
  
  MatrixXd inputs_grid;
  FunctionApproximator::generateInputsGrid(min, max, n_samples_per_dim, inputs_grid);
      
  const ModelParametersGPR* model_parameters_gpr = static_cast<const ModelParametersGPR*>(getModelParameters());

  MatrixXd activations_grid;
  model_parameters_gpr->kernelActivations(inputs_grid, activations_grid);
  
  saveMatrix(save_directory,"n_samples_per_dim.txt",n_samples_per_dim,overwrite);
  saveMatrix(save_directory,"inputs_grid.txt",inputs_grid,overwrite);
  saveMatrix(save_directory,"activations_grid.txt",activations_grid,overwrite);

  // Weight the basis function activations  
  VectorXd weights = model_parameters_gpr->weights();
  for (int b=0; b<activations_grid.cols(); b++)
    activations_grid.col(b).array() *= weights(b);
  saveMatrix(save_directory,"activations_weighted_grid.txt",activations_grid,overwrite);
  
  // Sum over weighed basis functions
  MatrixXd predictions_grid = activations_grid.rowwise().sum();
  saveMatrix(save_directory,"predictions_grid.txt",predictions_grid,overwrite);
  
  return true;
  
}
예제 #3
0
bool saveToDirectory(const UpdateSummary& summary, string directory, bool overwrite)
{
    // Make directory if it doesn't already exist
    if (!boost::filesystem::exists(directory))
    {
        if (!boost::filesystem::create_directories(directory))
        {
            cerr << __FILE__ << ":" << __LINE__ << ":";
            cerr << "Couldn't make directory file '" << directory << "'." << endl;
            return false;
        }
    }

    // Abbreviations to make it fit on one line
    bool ow = overwrite;
    string dir = directory;
    VectorXd cost_eval_vec = VectorXd::Constant(1,summary.cost_eval);

    if (!saveMatrix(dir, "distribution_mean.txt",  summary.distribution->mean(),  ow)) return false;
    if (!saveMatrix(dir, "distribution_covar.txt", summary.distribution->covar(), ow)) return false;
    if (!saveMatrix(dir, "cost_eval.txt",          cost_eval_vec,                 ow)) return false;
    if (!saveMatrix(dir, "samples.txt",            summary.samples,               ow)) return false;
    if (!saveMatrix(dir, "costs.txt",              summary.costs,                 ow)) return false;
    if (!saveMatrix(dir, "weights.txt",            summary.weights,               ow)) return false;
    if (!saveMatrix(dir, "distribution_new_mean.txt",  summary.distribution_new->mean(),  ow)) return false;
    if (!saveMatrix(dir, "distribution_new_covar.txt", summary.distribution_new->covar(), ow)) return false;

    if (summary.cost_vars_eval.size()>0)
        if (!saveMatrix(dir, "cost_vars_eval.txt",summary.cost_vars_eval, ow)) return false;
    if (summary.cost_vars.size()>0)
        if (!saveMatrix(dir, "cost_vars.txt",summary.cost_vars, ow)) return false;

    return true;

}
예제 #4
0
void testSaveMatrix(void) {
    FILE *matrixFile = fopen("test/matrix_to_save","wb");
    if(matrixFile == NULL) {
        return;
    } 
    
    size_t columns = 3;
    size_t rows = 3;
    floattype **matrix = AllocMatrix(rows, columns);
    floattype **expected = AllocMatrix(rows, columns);
    
    CU_ASSERT(CODE_OK == saveMatrix(matrix, matrixFile, rows, columns));
    FreeMatrix(matrix, rows);
    fclose(matrixFile);
    
    Matrix *matrixLoaded;
    FILE *loadFile = fopen("test/matrix_to_save","rb");
    matrixLoaded = loadMatrix(loadFile);
    fclose(loadFile);
    
    CU_ASSERT(NULL != matrixLoaded);
    if(NULL == matrixLoaded) {
        FreeMatrix(expected, rows);
        return;
    }
    
    CU_ASSERT(3 == matrixLoaded->header.colcount);
    CU_ASSERT(3 == matrixLoaded->header.rowcount);
    
    assertMatricesAreSame(expected, matrixLoaded->matrix, &(matrixLoaded->header));
    
    FreeMatrix(matrixLoaded->matrix, matrixLoaded->header.rowcount);
    free(matrixLoaded);
    FreeMatrix(expected, rows);
}
예제 #5
0
void F4Reducer::classicReducePolySet(
  const std::vector< std::unique_ptr<Poly> >& polys,
  const PolyBasis& basis,
  std::vector< std::unique_ptr<Poly> >& reducedOut
) {
  if (polys.size() <= 1) {
    if (tracingLevel >= 2)
      std::cerr << "F4Reducer: Using fall-back reducer for "
                << polys.size() << " polynomials.\n";
    mFallback->classicReducePolySet(polys, basis, reducedOut);
    return;
  }

  reducedOut.clear();

  MATHICGB_ASSERT(!polys.empty());
  if (tracingLevel >= 2)
    std::cerr << "F4Reducer: Reducing " << polys.size() << " polynomials.\n";

  SparseMatrix reduced;
  QuadMatrix::Monomials monomials;
  {
    QuadMatrix qm(ring());
    {
      if (mType == OldType) {
        F4MatrixBuilder builder(basis, mMemoryQuantum);
        for (const auto& poly : polys)
          builder.addPolynomialToMatrix(*poly);
        builder.buildMatrixAndClear(qm);
      } else {
        F4MatrixBuilder2 builder(basis, mMemoryQuantum);
        for (const auto& poly : polys)
          builder.addPolynomialToMatrix(*poly);
        builder.buildMatrixAndClear(qm);
      }
    }
    MATHICGB_LOG_INCREMENT_BY(F4MatrixRows, qm.rowCount());
    MATHICGB_LOG_INCREMENT_BY(F4MatrixTopRows, qm.topLeft.rowCount());
    MATHICGB_LOG_INCREMENT_BY(F4MatrixBottomRows, qm.bottomLeft.rowCount());
    MATHICGB_LOG_INCREMENT_BY(F4MatrixEntries, qm.entryCount());
    saveMatrix(qm);
    reduced = F4MatrixReducer(basis.ring().charac()).
      reducedRowEchelonFormBottomRight(qm);
    monomials = std::move(qm.rightColumnMonomials);
    for (auto& mono : qm.leftColumnMonomials)
      monoid().freeRaw(mono.castAwayConst());
  }

  if (tracingLevel >= 2 && false)
    std::cerr << "F4Reducer: Extracted " << reduced.rowCount()
              << " non-zero rows\n";

  for (SparseMatrix::RowIndex row = 0; row < reduced.rowCount(); ++row) {
    auto p = make_unique<Poly>(basis.ring());
    reduced.rowToPolynomial(row, monomials, *p);
    reducedOut.push_back(std::move(p));
  }
  for (auto& mono : monomials)
    monoid().freeRaw(mono.castAwayConst());
}
예제 #6
0
파일: matrix.c 프로젝트: pgasior/LAB_WDP_I
int main()
{
    double* m1,*m2;
    int m1rowCount=0,m1colCount=0,m2rowCount=0,m2colCount=0;
    m1=loadMatrix("m1.txt",&m1rowCount,&m1colCount);
    m2=loadMatrix("m2.txt",&m2rowCount,&m2colCount);
    printf("m1:\n");
    printMatrix(m1rowCount,m1colCount,m1);
    printf("\nm2:\n");
    printMatrix(m2rowCount,m2colCount,m2);
    printf("\n");
    if(m1colCount==m2rowCount)
    {
	double* m3 = product(m1rowCount,m1colCount,m2rowCount,m2colCount, m1,m2);
	printf("m1*m2:\n");
	printMatrix(m1rowCount,m2colCount,m3);
	saveMatrix("m3.txt",m1rowCount,m2colCount,m3);
	free(m3);
    }
    else
	printf("Nie mozna pomnozyc tych macierzy");
    free(m1);
    free(m2);
    return 0;
}
예제 #7
0
void SoftmaxLayer::runForwardImplementation(Bundle& bundle)
{
    auto& inputActivationsVector  = bundle[ "inputActivations"].get<MatrixVector>();
    auto& outputActivationsVector = bundle["outputActivations"].get<MatrixVector>();

    assert(inputActivationsVector.size() == 1);

    auto inputActivations = foldTime(inputActivationsVector.back());

    util::log("SoftmaxLayer") << " Running forward propagation of matrix "
        << inputActivations.shapeString() << "\n";

    if(util::isLogEnabled("SoftmaxLayer::Detail"))
    {
        util::log("SoftmaxLayer::Detail") << " input: "
            << inputActivations.debugString();
    }

    auto outputActivations = softmax(inputActivations);

    if(util::isLogEnabled("SoftmaxLayer::Detail"))
    {
        util::log("SoftmaxLayer::Detail") << " outputs: "
            << outputActivations.debugString();
    }

    saveMatrix("outputActivations", outputActivations);

    outputActivationsVector.push_back(unfoldTime(outputActivations,
        inputActivationsVector.front().size()));
}
예제 #8
0
/**
 * @param aXSide LEFT means we draw from the left side of the buffer (which
 * is drawn on the right side of mBufferRect). RIGHT means we draw from
 * the right side of the buffer (which is drawn on the left side of
 * mBufferRect).
 * @param aYSide TOP means we draw from the top side of the buffer (which
 * is drawn on the bottom side of mBufferRect). BOTTOM means we draw from
 * the bottom side of the buffer (which is drawn on the top side of
 * mBufferRect).
 */
void
ThebesLayerBuffer::DrawBufferQuadrant(gfxContext* aTarget,
                                      XSide aXSide, YSide aYSide,
                                      float aOpacity,
                                      gfxASurface* aMask,
                                      const gfxMatrix* aMaskTransform)
{
  // The rectangle that we're going to fill. Basically we're going to
  // render the buffer at mBufferRect + quadrantTranslation to get the
  // pixels in the right place, but we're only going to paint within
  // mBufferRect
  nsIntRect quadrantRect = GetQuadrantRectangle(aXSide, aYSide);
  nsIntRect fillRect;
  if (!fillRect.IntersectRect(mBufferRect, quadrantRect))
    return;

  aTarget->NewPath();
  aTarget->Rectangle(gfxRect(fillRect.x, fillRect.y,
                             fillRect.width, fillRect.height),
                     true);

  gfxPoint quadrantTranslation(quadrantRect.x, quadrantRect.y);
  nsRefPtr<gfxPattern> pattern = new gfxPattern(mBuffer);

#ifdef MOZ_GFX_OPTIMIZE_MOBILE
  gfxPattern::GraphicsFilter filter = gfxPattern::FILTER_NEAREST;
  pattern->SetFilter(filter);
#endif

  gfxContextMatrixAutoSaveRestore saveMatrix(aTarget);

  // Transform from user -> buffer space.
  gfxMatrix transform;
  transform.Translate(-quadrantTranslation);

  pattern->SetMatrix(transform);
  aTarget->SetPattern(pattern);

  if (aMask) {
    if (aOpacity == 1.0) {
      aTarget->SetMatrix(*aMaskTransform);
      aTarget->Mask(aMask);
    } else {
      aTarget->PushGroup(gfxASurface::CONTENT_COLOR_ALPHA);
      aTarget->Paint(aOpacity);
      aTarget->PopGroupToSource();
      aTarget->SetMatrix(*aMaskTransform);
      aTarget->Mask(aMask);
    }
  } else {
    if (aOpacity == 1.0) {
      aTarget->Fill();
    } else {
      aTarget->Save();
      aTarget->Clip();
      aTarget->Paint(aOpacity);
      aTarget->Restore();
    }
  }
}
예제 #9
0
파일: main.c 프로젝트: 8l/insieme
void saveAll(char* filePath, const char* filenameAdditon, double* VecSig, double* VecStr, double* VecDsig, double* VecDstr, double* InvF, double* InvFT, double* G,
		double* P11q, double* P22, double* P21, double* T3, double* Fe1q, double* Fe2, double* Fs, size_t nElems, size_t nVertices) {
	char path[512];
	sprintf(path, "%s%s", filePath, filenameAdditon);

	saveVector(VecSig, nElems, 14, path, "sig.sav");

	saveVector(VecStr, nElems, 20, path, "str.sav");

	saveVector(VecDsig, nElems, 14, path, "Dsig.sav");

	saveVector(VecDstr, nElems, 20, path, "Dstr.sav");

	saveMatrix(InvF, nElems, 14, 14, 14*14, path, "invF.sav");

	saveMatrix(InvFT, nElems, 14, 14, 14*14, path, "invFT.sav");

	saveMatrix(G, nElems, 20, 14, 24*14, path, "G.sav");

	saveMatrix(P11q, nElems, 14, 14, 14*14, path, "P11q.sav");

	saveMatrix(P21, nElems, 6, 14, 6*14, path, "P21.sav");

	saveMatrix(P22, nElems, 6, 6, 6*6, path, "P22.sav");

	saveMatrixT(T3, nVertices, 3, 2, 3*2, path, "T3.sav");

	saveVector(Fe1q, nElems, 14, path, "fe1q.sav");

	saveVector(Fe2, nElems, 6, path, "fe2.sav");

	saveVector(Fs, nElems, 14, path, "fs.sav");
}
예제 #10
0
bool saveToDirectory(const vector<UpdateSummaryParallel>& update_summaries, std::string directory, bool overwrite, bool only_learning_curve)
{
  
  // Save the learning curve
  int n_updates = update_summaries.size();  
  assert(n_updates>0);
  
  int n_parallel = update_summaries[0].distributions.size();
  MatrixXd learning_curve(n_updates,2+n_parallel);
  learning_curve(0,0) = 0; // First evaluation is at 0
  
  for (int i_update=0; i_update<n_updates; i_update++)
  {

    // Number of samples at which an evaluation was performed.
    if (i_update>0)
    {
      int n_samples = update_summaries[i_update].costs.rows();
      learning_curve(i_update,0) = learning_curve(i_update-1,0) + n_samples; 
    }
    
    // The cost of the evaluation at this update
    learning_curve(i_update,1) = update_summaries[i_update].cost_eval;
    
    for (int i_parallel=0; i_parallel<n_parallel; i_parallel++)
    {
      // The largest eigenvalue of the covariance matrix, for each distribution
      DistributionGaussian* distribution = update_summaries[i_update].distributions[i_parallel];
      MatrixXd eigen_values = distribution->covar().eigenvalues().real();
      learning_curve(i_update,2+i_parallel) = sqrt(eigen_values.maxCoeff());
    }
    
  }

  if (!saveMatrix(directory, "learning_curve.txt", learning_curve, overwrite))
    return false;
    
  if (!only_learning_curve)
  {
    // Save all the information in the update summaries
    for (int i_update=0; i_update<n_updates; i_update++)
    {
      stringstream stream;
      stream << directory << "/update" << setw(5) << setfill('0') << i_update+1 << "/";
      if (!saveToDirectory(update_summaries[i_update], stream.str(),overwrite))
        return false;
    }
  }
  return true;
}
예제 #11
0
int main(int argc, char* argv[])
{
    int lines, columns, qtd;
    printf("linhas: ");
    scanf("%d", &lines);
    printf("colunas: ");
    scanf("%d", &columns);
    printf("quantidade: ");
    scanf("%d", &qtd);
    int i;
    for(i = 0; i < qtd; i++)
    {
        int** matrix = randMatrixGen(lines, columns);
        saveMatrix(lines,columns, matrix, i);
    }
}
예제 #12
0
파일: main.cpp 프로젝트: KoltesDigital/Orb
int main()
{
	if (pthread_mutex_init(&mutex, nullptr))
	{
		return -1;
	}

	if (!gy85.initialize())
	{
		return -1;
	}

	if (!timer.initialize())
	{
		return -1;
	}

	running = true;

	pthread_create(&thread, nullptr, measure, nullptr);

	std::cin.get();

	if (pthread_mutex_lock(&mutex))
	{
		return shutdown(-1);
	}

	glm::vec3 accelerometer;
	gy85.getAccelerometer(accelerometer);

	glm::vec3 compass;
	gy85.getCompass(compass);

	glm::mat3 worldToCard;
	computeToWorldMatrix(accelerometer, compass, worldToCard);

	saveMatrix("rotation.calibration", worldToCard);

	pthread_mutex_unlock(&mutex);

	return shutdown(0);
}
예제 #13
0
DrawResult
ClippedImage::DrawSingleTile(gfxContext* aContext,
                             const nsIntSize& aSize,
                             const ImageRegion& aRegion,
                             uint32_t aWhichFrame,
                             GraphicsFilter aFilter,
                             const Maybe<SVGImageContext>& aSVGContext,
                             uint32_t aFlags)
{
  MOZ_ASSERT(!MustCreateSurface(aContext, aSize, aRegion, aFlags),
             "Shouldn't need to create a surface");

  gfxRect clip(mClip.x, mClip.y, mClip.width, mClip.height);
  nsIntSize size(aSize), innerSize(aSize);
  if (NS_SUCCEEDED(InnerImage()->GetWidth(&innerSize.width)) &&
      NS_SUCCEEDED(InnerImage()->GetHeight(&innerSize.height))) {
    double scaleX = aSize.width / clip.width;
    double scaleY = aSize.height / clip.height;

    // Map the clip and size to the scale requested by the caller.
    clip.Scale(scaleX, scaleY);
    size = innerSize;
    size.Scale(scaleX, scaleY);
  } else {
    MOZ_ASSERT(false,
               "If ShouldClip() led us to draw then we should never get here");
  }

  // We restrict our drawing to only the clipping region, and translate so that
  // the clipping region is placed at the position the caller expects.
  ImageRegion region(aRegion);
  region.MoveBy(clip.x, clip.y);
  region = region.Intersect(clip);

  gfxContextMatrixAutoSaveRestore saveMatrix(aContext);
  aContext->Multiply(gfxMatrix::Translation(-clip.x, -clip.y));

  return InnerImage()->Draw(aContext, size, region,
                            aWhichFrame, aFilter,
                            aSVGContext.map(UnclipViewport,
                                            make_pair(innerSize, mClip.Size())),
                            aFlags);
}
예제 #14
0
int main(int argc, char** argv)
{
    if(argc != 6) {
        printf("Usage: binary <size> <input1_file> <input2_file> <output_file> <coefficient>\n");
        return -1;
    }
    unsigned int size = atoi(argv[1]);
    float coef = atof(argv[5]);
    float* a = loadMatrix(argv[2], 1, size);
    float* b = loadMatrix(argv[3], 1, size);
    float* m = (float*) malloc (sizeof(float)*size);

    triad(m, a, b, coef, size);

    saveMatrix(argv[4], m, 1, size);
    free(a);
    free(b);
    free(m);
    systamp();
    return 0;
}
예제 #15
0
DrawResult
RasterImage::DrawInternal(DrawableSurface&& aSurface,
                          gfxContext* aContext,
                          const IntSize& aSize,
                          const ImageRegion& aRegion,
                          SamplingFilter aSamplingFilter,
                          uint32_t aFlags,
                          float aOpacity)
{
  gfxContextMatrixAutoSaveRestore saveMatrix(aContext);
  ImageRegion region(aRegion);
  bool frameIsFinished = aSurface->IsFinished();

  // By now we may have a frame with the requested size. If not, we need to
  // adjust the drawing parameters accordingly.
  IntSize finalSize = aSurface->GetImageSize();
  bool couldRedecodeForBetterFrame = false;
  if (finalSize != aSize) {
    gfx::Size scale(double(aSize.width) / finalSize.width,
                    double(aSize.height) / finalSize.height);
    aContext->Multiply(gfxMatrix::Scaling(scale.width, scale.height));
    region.Scale(1.0 / scale.width, 1.0 / scale.height);

    couldRedecodeForBetterFrame = CanDownscaleDuringDecode(aSize, aFlags);
  }

  if (!aSurface->Draw(aContext, region, aSamplingFilter, aFlags, aOpacity)) {
    RecoverFromInvalidFrames(aSize, aFlags);
    return DrawResult::TEMPORARY_ERROR;
  }
  if (!frameIsFinished) {
    return DrawResult::INCOMPLETE;
  }
  if (couldRedecodeForBetterFrame) {
    return DrawResult::WRONG_SIZE;
  }
  return DrawResult::SUCCESS;
}
예제 #16
0
bool UnifiedModel::saveGridData(const VectorXd& min, const VectorXd& max, const VectorXi& n_samples_per_dim, string save_directory, bool overwrite) const
{
  if (save_directory.empty())
    return true;  
 
#ifndef NDEBUG // Variables below are only required for asserts; check for NDEBUG to avoid warnings.
  int n_dims = min.size();
  assert(n_dims==max.size());
  assert(n_dims==n_samples_per_dim.size());
#endif

  MatrixXd inputs;
  FunctionApproximator::generateInputsGrid(min, max, n_samples_per_dim, inputs);

  MatrixXd lines;
  getLines(inputs, lines);
  
  MatrixXd activations;
  if (cosine_basis_functions_)
  {
    BasisFunction::Cosine::activations(covars_,centers_,inputs,activations);
  }
  else
  {
    BasisFunction::Gaussian::activations(centers_,covars_,priors_,inputs,activations,normalized_basis_functions_);
    if (normalized_basis_functions_)
    {
      MatrixXd unnormalized_activations;
      BasisFunction::Gaussian::activations(centers_,covars_,priors_,inputs,unnormalized_activations,false);
      saveMatrix(save_directory,"activations_unnormalized_grid.txt",unnormalized_activations,overwrite);
    }
  }
    
  MatrixXd predictions;
  evaluate(inputs,predictions);
  
  saveMatrix(save_directory,"n_samples_per_dim.txt",n_samples_per_dim,overwrite);
  saveMatrix(save_directory,"inputs_grid.txt",inputs,overwrite);
  saveMatrix(save_directory,"lines_grid.txt",lines,overwrite);
  saveMatrix(save_directory,"activations_grid.txt",activations,overwrite);
  saveMatrix(save_directory,"predictions_grid.txt",predictions,overwrite);
  
  return true;
  
}
예제 #17
0
int main(int argc, char** argv)
{
    if(argc != 7){
        printf("Usage: matmul <heightA> <widthA> <widthB> <file_MA> <file_MB> <output_file>\n");
        return -1;
    }
    unsigned int HA, WA, WB;
    HA = atoi(argv[1]);
    WA = atoi(argv[2]);
    WB = atoi(argv[3]);
    float* h_A = loadMatrix(argv[4], HA, WA);
    float* h_B = loadMatrix(argv[5], WA, WB);
    float* h_C = (float*) malloc(sizeof(float)*HA*WB);
    
    computeGold(h_C, h_A, h_B, HA, WA, WB);

    saveMatrix(argv[6], h_C, HA, WB);

    free(h_A);
    free(h_B);
    free(h_C);
    systamp();
    return 0;
}
예제 #18
0
파일: main.c 프로젝트: cegonse/Jacobi
int main (int argc, char* argv[])
{
	double conv = 0.001;
	int n, k = 0, save = 0;
	struct timeval t0, tf;
	double ep;
	double *A = NULL, *b = NULL, *x0 = NULL;
	
	if (argc < 2)
	{
		printf("Usage: jacobi [matrix_size] [--save]\n");
		exit(0);
	}
	else if (argc == 3)
	{
		if (strcmp("--save", argv[2]) == 0)
		{
			save = 1;
		}
		else
		{
			printf("Unrecognized option \"%s\".\n", argv[2]);
			printf("Usage: jacobi [matrix_size] [--save]\n");
			exit(0);
		}
	}
	
	n = atoi(argv[1]);
	
	A = (double*) malloc(sizeof(double)*n*n);
	b = (double*) malloc(sizeof(double)*n);
	x0 = (double*) malloc(sizeof(double)*n);
	
	// Creamos las matrices del problema
	k = generateMatrices(A, b, x0, n);
	
	if (k < 0)
	{
		fprintf(stderr, "Error generating input data: %s\n", strerror(k));
	}

	// Ejecutamos el problema
	gettimeofday(&t0, NULL);
	k = jacobi(A, b, x0, conv, n);
	gettimeofday(&tf, NULL);
	
	if (k < 0)
	{
		fprintf(stderr, "Error obtaining Jacobi solution: %s\n", strerror(k));
	}
	
	ep = (tf.tv_sec - t0.tv_sec) + (tf.tv_usec - t0.tv_usec) / 1000000.0;
	
	// Borramos los datos inicializados al inicio del problema
	// y mostramos las estadísticas (tamaño matriz, iteraciones y tiempo).
	// Si se ha especificado, guardamos el resultado como archivo DLM.
	setlocale(LC_NUMERIC, "es_ES.UTF-8");
	printf("%d;%d;%.6f\n", n, k, ep);
	
	if (save)
	{
		saveMatrix("x", x0, n, 1);
		saveMatrix("A", A, n, 2);
		saveMatrix("b", b, n, 1);
	}
	
	free(A);
	free(b);
	free(x0);
	
	return 0;
}
예제 #19
0
파일: Trajectory.cpp 프로젝트: humm/dovecot
bool Trajectory::saveToFile(string directory, string filename, bool overwrite) const
{
    MatrixXd traj_matrix(length(),1+3*dim()+dim_misc());
    traj_matrix << ts_, ys_, yds_, ydds_, misc_;
    return saveMatrix(directory, filename, traj_matrix, overwrite);
}
예제 #20
0
int main(void) {

	std::string filePath = "CNN-DocTermCountMatrix.txt";
	Matrix& X_Ori = loadMatrix(filePath);
	int NSample = min(20, X_Ori.getRowDimension());
	Matrix& X = X_Ori.getSubMatrix(0, NSample - 1, 0, X_Ori.getColumnDimension() - 1);
	// disp(X.getSubMatrix(0, 10, 0, 100));
	println(sprintf("%d samples loaded", X.getRowDimension()));
	GraphOptions& options = *new GraphOptions();
	options.graphType = "nn";
	std::string type = options.graphType;
	double NN = options.graphParam;
	fprintf("Graph type: %s with NN: %d\n", type.c_str(), (int)NN);

	// Parameter setting for text data
	options.kernelType = "cosine";
	options.graphDistanceFunction = "cosine";

	// Parameter setting for image data
	/*options.kernelType = "rbf";
			options.graphDistanceFunction = "euclidean";*/

	options.graphNormalize = true;
	options.graphWeightType = "heat";

	bool show = true && !false;

	// Test adjacency function - pass
	tic();
	std::string DISTANCEFUNCTION = options.graphDistanceFunction;
	Matrix& A = adjacency(X, type, NN, DISTANCEFUNCTION);
	fprintf("Elapsed time: %.2f seconds.\n", toc());
	std::string adjacencyFilePath = "adjacency.txt";
	saveMatrix(adjacencyFilePath, A);
	if (show)
		disp(A.getSubMatrix(0, 4, 0, 4));

	// Test laplacian function - pass
	tic();
	Matrix& L = laplacian(X, type, options);
	fprintf("Elapsed time: %.2f seconds.\n", toc());
	std::string LaplacianFilePath = "Laplacian.txt";
	saveMatrix(LaplacianFilePath, L);
	if (show)
		disp(L.getSubMatrix(0, 4, 0, 4));

	// Test local learning regularization - pass
	NN = options.graphParam;
	std::string DISTFUNC = options.graphDistanceFunction;
	std::string KernelType = options.kernelType;
	double KernelParam = options.kernelParam;
	double lambda = 0.001;
	tic();
	Matrix& LLR_text = calcLLR(X, NN, DISTFUNC, KernelType, KernelParam, lambda);
	fprintf("Elapsed time: %.2f seconds.\n", toc());
	std::string LLRFilePath = "localLearningRegularization.txt";
	saveMatrix(LLRFilePath, LLR_text);
	if (show)
		display(LLR_text.getSubMatrix(0, 4, 0, 4));

	return EXIT_SUCCESS;

}
예제 #21
0
int main(int argc, char* argv[])
{
	int i;
	int status;

	if(argc < 2)
	{
		printf("Please provide a number of processes\n");
		exit(0);
	}

	p = atoi(argv[1]);

	if(p <= 0)
	{
		printf("The number of processes must be an integer larger than 0\n");
		exit(0);
	}

	status = init();

	switch(status)
	{
		case MATRIX1_ERROR:
			printf("Error reading in1.txt\n");
			exit(0);
		case MATRIX2_ERROR:
			printf("Error reading in2.txt\n");
			exit(0);
		case INCOMPATIBLE_ERROR:
			printf("Matrices are incompatible\n");
			exit(0);
		default: /* case SUCCESS: */
			break;
	}

	resultMatrix = (int**) calloc(m, sizeof(int*));

	pthread_t* pthreads = (pthread_t*) calloc(p, sizeof(pthread_t));
	int* threadNumber = (int*) calloc(p, sizeof(int));

	for(i = 0; i < p; i++)
	{
		threadNumber[i] = i;

		pthread_create(pthreads + i, NULL, fillMatrix, threadNumber + i);
	}

	for(i = 0; i < p; i++)
	{
		pthread_join(pthreads[i], NULL);
	}

	int success = saveMatrix(m, n, resultMatrix);

	if(!success)
	{
		printf("Couldn't write to file out.txt");
	}

	for(i = 0; i < m; i++)
	{
		free(matrix1[i]);
	}

	free(matrix1);

	for(i = 0; i < x; i++)
	{
		free(matrix2[i]);
	}

	free(matrix2);

	for(i = 0; i < m; i++)
	{
		free(resultMatrix[i]);
	}

	free(resultMatrix);

	return 0;
}
예제 #22
0
bool saveToDirectory(const UpdateSummaryParallel& summary, string directory, bool overwrite)
{

  // Make directory if it doesn't already exist
  if (!boost::filesystem::exists(directory))
  {
    if (!boost::filesystem::create_directories(directory))
    {
      cerr << __FILE__ << ":" << __LINE__ << ":";
      cerr << "Couldn't make directory file '" << directory << "'." << endl;
      return false;
    }
  }

  // Abbreviations to make it fit on one line
  bool ow = overwrite;
  string dir = directory;
  VectorXd cost_eval_vec = VectorXd::Constant(1,summary.cost_eval);
  
  if (!saveMatrix(dir, "cost_eval.txt",          cost_eval_vec,                 ow)) return false;
  if (!saveMatrix(dir, "costs.txt",              summary.costs,                 ow)) return false;
  if (!saveMatrix(dir, "weights.txt",            summary.weights,               ow)) return false;
  if (summary.cost_vars_eval.size()>0)
    if (!saveMatrix(dir, "cost_vars_eval.txt",summary.cost_vars_eval, ow)) return false;
  if (summary.cost_vars.size()>0)
    if (!saveMatrix(dir, "cost_vars.txt",summary.cost_vars, ow)) return false;

  int n_parallel = summary.distributions.size();
  VectorXi n_parallel_vec = VectorXi::Constant(1,n_parallel);
  saveMatrix(directory,"n_parallel.txt",n_parallel_vec,overwrite);
  
  for (int ii=0; ii<n_parallel; ii++)
  {
    stringstream stream;
    stream << "_" << setw(2) << setfill('0') << ii << ".txt";
    string suf = stream.str();
    if (!saveMatrix(dir, "distribution_mean"+suf,  summary.distributions[ii]->mean(),  ow))
      return false;
    if (!saveMatrix(dir, "distribution_covar"+suf, summary.distributions[ii]->covar(), ow)) 
      return false;
    if (!saveMatrix(dir, "samples"+suf,            summary.samples[ii],               ow)) 
      return false;
    if (!saveMatrix(dir, "distribution_new_mean"+suf,  summary.distributions_new[ii]->mean(),  ow)) 
      return false;
    if (!saveMatrix(dir, "distribution_new_covar"+suf, summary.distributions_new[ii]->covar(), ow)) 
      return false;
  }  
  
  return true;
  
}
예제 #23
0
int main(int argc, char** argv)
{
	int n=0, j, k, i;
	Matrix* matrix;

	printf("Input the number of rows and columns of the matrix: ");
	scanf("%d", &n);
	
	if(n<0) n=0;

	/*
	 * Test 1
	 */
	matrix = newMatrix(n, F);

	i=1;
	for(j=0; j<n; j++) {
		for(k=0; k<n; k++) {
			setMatrixEntry(matrix, i, j, k);
			i++;
		}
	}
	
	printf("F-Matrix before save:\n");
	printMatrix(matrix);

	saveMatrix(FILENAME, matrix);

	matrix = delMatrix(matrix);

	matrix = loadMatrix(FILENAME, n);

	printf("F-Matrix after load:\n");
	printMatrix(matrix);
	
	matrix = delMatrix(matrix);

	/*
	 * Test 2
	 */
	matrix = newMatrix(n, L);

	i=1;
	for(j=0; j<n; j++) {
		for(k=0; k<=j; k++) {
			setMatrixEntry(matrix, i, j, k);
			i++;
		}
	}
	
	printf("L-Matrix before save:\n");
	printMatrix(matrix);

	saveMatrix(FILENAME, matrix);

	matrix = delMatrix(matrix);

	matrix = loadMatrix(FILENAME, n);

	printf("L-Matrix after load:\n");
	printMatrix(matrix);

	matrix = isLmatrix(matrix);
	if(matrix == NULL)
		return EXIT_FAILURE;

	printf("L-Matrix conversion:\n");
	printMatrix(matrix);
	
	matrix = delMatrix(matrix);

	/*
	 * Test 3
	 */
	matrix = newMatrix(n, U);

	i=1;
	for(j=0; j<n; j++) {
		for(k=j; k<n; k++) {
			setMatrixEntry(matrix, i, j, k);
			i++;
		}
	}
	
	printf("U-Matrix before save:\n");
	printMatrix(matrix);

	saveMatrix(FILENAME, matrix);

	matrix = delMatrix(matrix);

	matrix = loadMatrix(FILENAME, n);

	printf("U-Matrix after load:\n");
	printMatrix(matrix);

	matrix = isUmatrix(matrix);
	if(matrix == NULL)
		return EXIT_FAILURE;

	printf("U-Matrix conversion:\n");
	printMatrix(matrix);
	
	matrix = delMatrix(matrix);

	return EXIT_SUCCESS;
}
예제 #24
0
DrawResult
ClippedImage::DrawSingleTile(gfxContext* aContext,
                             const nsIntSize& aSize,
                             const ImageRegion& aRegion,
                             uint32_t aWhichFrame,
                             SamplingFilter aSamplingFilter,
                             const Maybe<SVGImageContext>& aSVGContext,
                             uint32_t aFlags)
{
  MOZ_ASSERT(!MustCreateSurface(aContext, aSize, aRegion, aFlags),
             "Shouldn't need to create a surface");

  gfxRect clip(mClip.x, mClip.y, mClip.width, mClip.height);
  nsIntSize size(aSize), innerSize(aSize);
  bool needScale = false;
  if (mSVGViewportSize && !mSVGViewportSize->IsEmpty()) {
    innerSize = *mSVGViewportSize;
    needScale = true;
  } else if (NS_SUCCEEDED(InnerImage()->GetWidth(&innerSize.width)) &&
             NS_SUCCEEDED(InnerImage()->GetHeight(&innerSize.height))) {
    needScale = true;
  } else {
    MOZ_ASSERT_UNREACHABLE(
               "If ShouldClip() led us to draw then we should never get here");
  }

  if (needScale) {
    double scaleX = aSize.width / clip.width;
    double scaleY = aSize.height / clip.height;

    // Map the clip and size to the scale requested by the caller.
    clip.Scale(scaleX, scaleY);
    size = innerSize;
    size.Scale(scaleX, scaleY);
  }

  // We restrict our drawing to only the clipping region, and translate so that
  // the clipping region is placed at the position the caller expects.
  ImageRegion region(aRegion);
  region.MoveBy(clip.x, clip.y);
  region = region.Intersect(clip);

  gfxContextMatrixAutoSaveRestore saveMatrix(aContext);
  aContext->Multiply(gfxMatrix::Translation(-clip.x, -clip.y));

  auto unclipViewport = [&](const SVGImageContext& aOldContext) {
    // Map the viewport to the inner image. Note that we don't take the aSize
    // parameter of imgIContainer::Draw into account, just the clipping region.
    // The size in pixels at which the output will ultimately be drawn is
    // irrelevant here since the purpose of the SVG viewport size is to
    // determine what *region* of the SVG document will be drawn.
    CSSIntSize vSize(aOldContext.GetViewportSize());
    vSize.width = ceil(vSize.width * double(innerSize.width) / mClip.width);
    vSize.height =
      ceil(vSize.height * double(innerSize.height) / mClip.height);

    return SVGImageContext(vSize,
                           aOldContext.GetPreserveAspectRatio());
  };

  return InnerImage()->Draw(aContext, size, region,
                            aWhichFrame, aSamplingFilter,
                            aSVGContext.map(unclipViewport),
                            aFlags);
}
예제 #25
0
int main(void) {

	std::string filePath = "CNN-DocTermCountMatrix.txt";
	tic();
	Matrix* X = null;
	X = &loadMatrix(filePath);
	/*Matrix& Y = X->getSubMatrix(0, 29, 0, 999);
	saveMatrix(Y, "CNN-SubDocTermCountMatrix.txt");*/

	/*double data[3][4] = {
				{3.5, 5.3, 0.2, -1.2},
				{4.4, 2.2, 0.3, 0.4},
				{1.3, 0.5, 4.1, 3.2}
		};
	X = &DenseMatrix::createDenseMatrix<4>(data, 3, 4);*/

	X = &X->transpose();
	X = &getTFIDF(*X);
	X = &normalizeByColumns(*X);
	X = &X->transpose();

	KMeansOptions& kMeansOptions = *new KMeansOptions();
	kMeansOptions.nClus = 10;
	kMeansOptions.maxIter = 50;
	kMeansOptions.verbose = true;

	Clustering& kmeans = *new KMeans(kMeansOptions);
	kmeans.feedData(*X);
	// KMeans.initialize(null);
	kmeans.clustering();

	Matrix* G0 = kmeans.getIndicatorMatrix();
	/*disp("G0:");
	printMatrix(*G0);*/

	// Matrix X = Data.loadSparseMatrix("X.txt");
	// G0 = loadDenseMatrix("G0.txt");
	NMFOptions& nmfOptions = *new NMFOptions();
	nmfOptions.nClus = 10;
	nmfOptions.maxIter = 300;
	nmfOptions.verbose = true;
	nmfOptions.calc_OV = !true;
	nmfOptions.epsilon = 1e-5;
	Clustering& nmf = *new NMF(nmfOptions);
	nmf.feedData(*X);
	// L1NMF.initialize(G0);

	// Matlab takes 12.5413 seconds
	// jblas takes 29.368 seconds
	// Commons-math takes 129 seconds (Using Array2DRowRealMatrix)
	// Commons-math takes 115 seconds (Using DenseMatrix)
	// start = System.currentTimeMillis();

	nmf.clustering(G0); // Use null for random initialization

	fprintf("Elapsed time: %.3f seconds\n", toc());
	/*disp(*nmf.getCenters());
	disp(*nmf.getIndicatorMatrix());*/

	saveMatrix("F.txt", *nmf.getCenters());
	saveMatrix("G.txt", *nmf.getIndicatorMatrix());

	return EXIT_SUCCESS;

}
예제 #26
0
void runOptimizationTask(
  const Task* const task, 
  const TaskSolver* const task_solver, 
  const DistributionGaussian* const initial_distribution, 
  const Updater* const updater, 
  int n_updates, 
  int n_samples_per_update, 
  std::string save_directory, 
  bool overwrite,
  bool only_learning_curve)
{
  
  int n_cost_components = task->getNumberOfCostComponents();

  // Some variables
  VectorXd sample_eval;
  MatrixXd cost_vars_eval;
  VectorXd cost_eval(1+n_cost_components);
  
  MatrixXd samples;
  MatrixXd cost_vars;
  VectorXd weights;
  MatrixXd costs(n_samples_per_update,1+n_cost_components);
  
  // tmp variables
  VectorXd total_costs(n_samples_per_update);
  VectorXd cur_cost(1+n_cost_components);
  
  // Bookkeeping
  MatrixXd learning_curve(n_updates,2+n_cost_components);
  MatrixXd exploration_curve(n_updates,2);
  
  if (save_directory.empty()) 
    cout << "init  =  " << "  distribution=" << *initial_distribution;
  
  DistributionGaussian distribution = *(initial_distribution->clone());
  DistributionGaussian distribution_new = *(initial_distribution->clone());
  
  // Optimization loop
  for (int i_update=0; i_update<n_updates; i_update++)
  {
    // 0. Get cost of current distribution mean
    sample_eval = distribution.mean().transpose();
    task_solver->performRollout(sample_eval,cost_vars_eval);
    task->evaluateRollout(cost_vars_eval,sample_eval,cost_eval);
    Rollout* rollout_eval = new Rollout(sample_eval,cost_vars_eval,cost_eval);
    
    // 1. Sample from distribution
    distribution.generateSamples(n_samples_per_update, samples);

    vector<Rollout*> rollouts(n_samples_per_update);
    for (int i_sample=0; i_sample<n_samples_per_update; i_sample++)
    {
      // 2A. Perform the rollout
      task_solver->performRollout(samples.row(i_sample),cost_vars);

      // 2B. Evaluate the rollout
      task->evaluateRollout(cost_vars,samples.row(i_sample),cur_cost);
      costs.row(i_sample) = cur_cost;

      rollouts[i_sample] = new Rollout(samples.row(i_sample),cost_vars,cur_cost);
      
    }
  
    // 3. Update parameters (first column of costs contains sum of cost components)
    total_costs = costs.col(0);
    updater->updateDistribution(distribution, samples, total_costs, weights, distribution_new);
    
    
    // Bookkeeping
    // Some output and/or saving to file (if "directory" is set)
    if (save_directory.empty()) 
    {
      cout << "\t cost_eval=" << cost_eval << endl << i_update+1 << "  " << distribution;
    }
    else
    {
      // Update learning curve
      // How many samples?
      int i_samples = i_update*n_samples_per_update;
      learning_curve(i_update,0) = i_samples;
      // Cost of evaluation
      learning_curve.block(i_update,1,1,1+n_cost_components) = cost_eval.transpose();
      
      // Exploration magnitude
      exploration_curve(i_update,0) = i_samples;
      exploration_curve(i_update,1) = sqrt(distribution.maxEigenValue()); 
      
      // Save more than just learning curve.
      if (!only_learning_curve)
      {
          saveToDirectory(save_directory,i_update,distribution,rollout_eval,rollouts,weights,distribution_new);
          if (i_update==0)
            task->savePlotRolloutScript(save_directory);
      }
    }
    
    // Distribution is new distribution
    distribution = distribution_new;
    
  }
  
  // Save learning curve to file, if necessary
  if (!save_directory.empty())
  {
    // Todo: save cost labels also
    saveMatrix(save_directory, "exploration_curve.txt",exploration_curve,overwrite);
    saveMatrix(save_directory, "learning_curve.txt",learning_curve,overwrite);
  }
}
예제 #27
0
파일: matmult.cpp 프로젝트: XzzX/SiWiR_ex1
int main(int argc, char **argv) {
	///******************************************************
	///********************** INPUT *************************
	///******************************************************
	if (argc != 4) {
		std::cout << "Invalid number of arguments!" << std::endl;
		std::cout << "./compare A.out B.out" << std::endl;
		exit(EXIT_FAILURE);
	}

	//matrix dimensions
	int dimM = 0;
	int dimN = 0;
	int dimO = 0;

	//get dimensions
	std::ifstream	fIn(argv[1]);
	if (!fIn) {
		std::cout << "Error opening file: " << argv[1] << std::endl;
		exit(EXIT_FAILURE);
	}

	if(!(fIn >> dimM >> dimN))
	{
		std::cout << "Error in reading matrix entries!" << std::endl;
		exit(EXIT_FAILURE);
	}
	fIn.close();

	fIn.open(argv[2]);
	if (!fIn) {
		std::cout << "Error opening file: " << argv[2] << std::endl;
		exit(EXIT_FAILURE);
	}

	if(!(fIn >> dimN >> dimO))
	{
		std::cout << "Error in reading matrix entries!" << std::endl;
		exit(EXIT_FAILURE);
	}

	fIn.close();

	//calculate minimal matrix size
	//all matrices are padded with 0s to this size
	//should be power of 2 for efficient block division
	//dirty hack...
	LD = 64;
	if (LD<dimM) LD = dimM;
	if (LD<dimN) LD = dimN;
	if (LD<dimO) LD = dimO;

	LD--;
	LD |= LD >> 1;
	LD |= LD >> 2;
	LD |= LD >> 4;
	LD |= LD >> 8;
	LD |= LD >> 16;
	LD++;

	//add useless padding
	LD += PADDING;

	double* a = (double*) aligned_alloc(ALIGNMENT, sizeof(double) * LD * LD);
	double* b = (double*) aligned_alloc(ALIGNMENT, sizeof(double) * LD * LD);
	double* c = (double*) aligned_alloc(ALIGNMENT, sizeof(double) * LD * LD);

	Matrix	A = loadMatrix(argv[1], &a[0]);
	Matrix	B = loadMatrix(argv[2], &b[0]);
	Matrix	C(&c[0], nullptr, A.getDimM(), B.getDimN(), 0, 0);

	///******************************************************
	///********************** CALCULATION *******************
	///******************************************************
	double time = 0;
	
#ifdef USE_LIKWID
	likwid_markerInit();
	likwid_markerStartRegion("dummy");
#endif

	siwir::Timer	timer;

	MMM(A, B, C);

	time = timer.elapsed();
	std::cout << dimM << "\t" << dimN << "\t" << dimO << "\t" << time << std::endl;

#ifdef USE_LIKWID
	likwid_markerStopRegion("dummy");
	likwid_markerClose();
#endif

	///******************************************************
	///********************** OUTPUT ************************
	///******************************************************

	saveMatrix(argv[3], C);

	free(a);
	free(b);
	free(c);
};
예제 #28
0
void BundlerMatcher::open(const std::string& inputPath, const std::string& inputFilename, const std::string& outMatchFilename)
{
    mInputPath = inputPath;

    if (!mIsInitialized)
    {
        std::cout << "Error : can not initialize opengl context for SiftGPU" <<std::endl;
        return;
    }

    if (!parseListFile(inputFilename))
    {
        std::cout << "Error : can not open file : " <<inputFilename.c_str() <<std::endl;
        return;
    }

    //Sift Feature Extraction
    for (unsigned int i=0; i<mFilenames.size(); ++i)
    {
        int percent = (int)(((i+1)*100.0f) / (1.0f*mFilenames.size()));
        int nbFeature = extractSiftFeature(i);
        clearScreen();
        std::cout << "[Extracting Sift Feature : " << percent << "%] - ("<<i+1<<"/"<<mFilenames.size()<<", #"<< nbFeature <<" features)";
    }
    clearScreen();
    std::cout << "[Sift Feature extracted]"<<std::endl;

    for (unsigned int i=0; i<mFilenames.size(); ++i)
    {
        int percent = (int)(((i+1)*100.0f) / (1.0f*mFilenames.size()));
        saveAsciiKeyFile(i);
        if (mBinaryKeyFileWritingEnabled)
            saveBinaryKeyFile(i);
        clearScreen();
        std::cout << "[Saving Sift Key files: " << percent << "%] - ("<<i+1<<"/"<<mFilenames.size()<<")";
    }
    saveVector();
    clearScreen();
    std::cout << "[Sift Key files saved]"<<std::endl;

    delete mSift;
    mSift = NULL;

    mMatcher->VerifyContextGL();

    //Sift Matching
    int currentIteration = 0;

    if (mSequenceMatchingEnabled) //sequence matching (video input)
    {
        std::cout << "[Sequence matching enabled: length " << mSequenceMatchingLength << "]" << std::endl;
        int maxIterations = (int) (mFilenames.size()-mSequenceMatchingLength)*mSequenceMatchingLength + mSequenceMatchingLength*(mSequenceMatchingLength-1)/2; // (N-m).m + m(m-1)/2
        for (unsigned int i=0; i<mFilenames.size()-1; ++i)
        {
            for (int j=1; j<=mSequenceMatchingLength; ++j)
            {
                int indexA = i;
                int indexB = i+j;

                if (indexB >= mFilenames.size())
                    continue;
                else
                {
                    clearScreen();
                    int percent = (int) (currentIteration*100.0f / maxIterations*1.0f);
                    std::cout << "[Matching Sift Feature : " << percent << "%] - (" << indexA << "/" << indexB << ")";
                    matchSiftFeature(indexA, indexB);
                    currentIteration++;
                }
            }
        }
    }
    else //classic quadratic matching
    {
        int maxIterations = (int) mFilenames.size()*((int) mFilenames.size()-1)/2; // Sum(1 -> n) = n(n-1)/2
        for (unsigned int i=0; i<mFilenames.size(); ++i)
        {
            for (unsigned int j=i+1; j<mFilenames.size(); ++j)
            {
                clearScreen();
                int percent = (int) (currentIteration*100.0f / maxIterations*1.0f);
                std::cout << "[Matching Sift Feature : " << percent << "%] - (" << i << "/" << j << ")";
                matchSiftFeature(i, j);
                currentIteration++;
            }
        }
    }

    clearScreen();
    std::cout << "[Sift Feature matched]"<<std::endl;

    delete mMatcher;
    mMatcher = NULL;

    saveMatches(outMatchFilename);
    saveMatrix();
}
예제 #29
0
void FunctionApproximator::train(const MatrixXd& inputs, const MatrixXd& targets, string save_directory, bool overwrite)
{
  train(inputs,targets);
  
  if (save_directory.empty())
    return;
  
  if (!isTrained())
    return;
  
  if (getExpectedInputDim()<3)
  {
    
    VectorXd min = inputs.colwise().minCoeff();
    VectorXd max = inputs.colwise().maxCoeff();
    
    int n_samples_per_dim = 100;
    if (getExpectedInputDim()==2) n_samples_per_dim = 40;
    VectorXi n_samples_per_dim_vec = VectorXi::Constant(getExpectedInputDim(),n_samples_per_dim);

    model_parameters_->saveGridData(min, max, n_samples_per_dim_vec, save_directory, overwrite);
    
  }

  MatrixXd outputs;
  predict(inputs,outputs);

  saveMatrix(save_directory,"inputs.txt",inputs,overwrite);
  saveMatrix(save_directory,"targets.txt",targets,overwrite);
  saveMatrix(save_directory,"outputs.txt",outputs,overwrite);
  
  string filename = save_directory+"/plotdata.py";
  ofstream outfile;
  outfile.open(filename.c_str()); 
  if (!outfile.is_open())
  {
    cerr << __FILE__ << ":" << __LINE__ << ":";
    cerr << "Could not open file " << filename << " for writing." << endl;
  } 
  else
  {
    // Python code generation in C++. Rock 'n' roll! ;-)
    if (inputs.cols()==2) {                                                                                           
      outfile << "from mpl_toolkits.mplot3d import Axes3D                                       \n";
    }
    outfile   << "import numpy                                                                  \n";
    outfile   << "import matplotlib.pyplot as plt                                               \n";
    outfile   << "directory = '" << save_directory << "'                                        \n";
    outfile   << "inputs   = numpy.loadtxt(directory+'/inputs.txt')                             \n";
    outfile   << "targets  = numpy.loadtxt(directory+'/targets.txt')                            \n";
    outfile   << "outputs  = numpy.loadtxt(directory+'/outputs.txt')                            \n";
    outfile   << "fig = plt.figure()                                                            \n";
    if (inputs.cols()==2) {                                                                                           
      outfile << "ax = Axes3D(fig)                                                              \n";
      outfile << "ax.plot(inputs[:,0],inputs[:,1],targets, '.', label='targets',color='black')  \n";
      outfile << "ax.plot(inputs[:,0],inputs[:,1],outputs, '.', label='predictions',color='red')\n";
      outfile << "ax.set_xlabel('input_1'); ax.set_ylabel('input_2'); ax.set_zlabel('output')   \n";
      outfile << "ax.legend(loc='lower right')                                                  \n";
    } else {                                                                                           
      outfile << "plt.plot(inputs,targets, '.', label='targets',color='black')                  \n";
      outfile << "plt.plot(inputs,outputs, '.', label='predictions',color='red')                \n";
      outfile << "plt.xlabel('input'); plt.ylabel('output');                                    \n";
      outfile << "plt.legend(loc='lower right')                                                 \n";
    }                                                                                           
    outfile   << "plt.show()                                                                    \n";
    outfile << endl;

    outfile.close();
    //cout << "        ______________________________________________________________" << endl;
    //cout << "        | Plot saved data with:" << " 'python " << filename << "'." << endl;
    //cout << "        |______________________________________________________________" << endl;
  }
  
}
예제 #30
0
void CTCDecoderLayer::runForwardImplementation(Bundle& bundle)
{
    auto& inputActivationsVector  = bundle[ "inputActivations"].get<MatrixVector>();
    auto& outputActivationsVector = bundle["outputActivations"].get<MatrixVector>();

    assert(inputActivationsVector.size() == 1);

    auto inputActivations = inputActivationsVector.back();

    saveMatrix("inputActivations", inputActivations);

    auto beamSearchOutputSize = matrix::getBeamSearchOutputSize(
        inputActivations.size(), _implementation->getBeamSize());

    size_t miniBatchSize = inputActivations.size()[inputActivations.size().size() - 2];
    size_t timesteps     = inputActivations.size()[inputActivations.size().size() - 1];

    Matrix inputPaths({_implementation->getBeamSize(), miniBatchSize, timesteps},
        inputActivations.precision());
    Matrix outputActivations(beamSearchOutputSize, inputActivations.precision());
    Matrix outputActivationWeights({_implementation->getBeamSize(), miniBatchSize},
        inputActivations.precision());

    matrix::ctcBeamSearch(outputActivationWeights, inputPaths, outputActivations,
        inputActivations, _implementation->getBeamSize());

    reshapeOutputActivations(outputActivations, inputActivations.size(),
        _implementation->getBeamSize());

    bundle["outputActivationWeights"] = outputActivationWeights;

    saveMatrix("outputActivationWeights", outputActivationWeights);
    saveMatrix("inputPaths",              inputPaths);

    if(util::isLogEnabled("CTCDecoderLayer::Detail"))
    {
        util::log("CTCDecoderLayer::Detail") << "  output activation: "
            << outputActivations.debugString();
        util::log("CTCDecoderLayer::Detail") << "  input paths: "
            << inputPaths.debugString();
        util::log("CTCDecoderLayer::Detail") << "  output activation weights: "
            << outputActivationWeights.debugString();
    }
    else
    {
        util::log("CTCDecoderLayer") << "  output activation size: "
            << outputActivations.shapeString() << "\n";
        util::log("CTCDecoderLayer") << "  input paths: "
            << inputPaths.shapeString() << "\n";
        util::log("CTCDecoderLayer") << "  output activation weights: "
            << outputActivationWeights.shapeString() << "\n";
    }

    _implementation->saveInputLabels(   bundle["referenceLabels"].get<LabelVector>());
    _implementation->saveInputTimesteps(bundle["inputTimesteps" ].get<IndexVector>());

    outputActivationsVector.push_back(outputActivations);

    expandLabels(bundle, _implementation->getBeamSize());

    if(_implementation->hasCostFunction())
    {
        auto inputTimesteps = _implementation->getInputTimesteps();
        auto inputLabels    = _implementation->getInputLabels();

        computeCtcCosts(bundle, _implementation->getCostFunctionName(),
            _implementation->getCostFunctionWeight(),
            inputActivations, inputLabels, inputTimesteps);
    }
}