Exemple #1
0
 void CSMatrix<Scalar>::free()
 {
   nnz = 0;
   free_with_check(Ap);
   free_with_check(Ai);
   free_with_check(Ax);
 }
Exemple #2
0
    void CSMatrix<Scalar>::switch_orientation()
    {
      // The variable names are so to reflect CSC -> CSR direction.
      // From the "Ap indexed by columns" to "Ap indexed by rows".
      int* tempAp = malloc_with_check<CSMatrix<Scalar>, int>(this->size + 1, this);
      int* tempAi = malloc_with_check<CSMatrix<Scalar>, int>(nnz, this);
      Scalar* tempAx = malloc_with_check<CSMatrix<Scalar>, Scalar>(nnz, this);

      int run_i = 0;
      for (int target_row = 0; target_row < this->size; target_row++)
      {
        tempAp[target_row] = run_i;
        for (int src_column = 0; src_column < this->size; src_column++)
        {
          for (int src_row = this->Ap[src_column]; src_row < this->Ap[src_column + 1]; src_row++)
          {
            if (this->Ai[src_row] == target_row)
            {
              tempAi[run_i] = src_column;
              tempAx[run_i++] = this->Ax[src_row];
            }
          }
        }
      }

      tempAp[this->size] = this->nnz;
      memcpy(this->Ai, tempAi, sizeof(int)* nnz);
      memcpy(this->Ap, tempAp, sizeof(int)* (this->size + 1));
      memcpy(this->Ax, tempAx, sizeof(Scalar)* nnz);
      free_with_check(tempAi);
      free_with_check(tempAx);
      free_with_check(tempAp);
    }
Exemple #3
0
    void PetscMatrix<Scalar>::alloc()
    {
      assert(this->pages != nullptr);

      // calc nnz
      int *nnz_array = malloc_with_check(this->size, this);

      // fill in nnz_array
      int aisize = this->get_num_indices();
      int *ai = malloc_with_check(aisize, this);

      // sort the indices and remove duplicities, insert into ai
      int pos = 0;
      for (unsigned int i = 0; i < this->size; i++)
      {
        nnz_array[i] = this->sort_and_store_indices(this->pages[i], ai + pos, ai + aisize);
        pos += nnz_array[i];
      }
      // stote the number of nonzeros
      nnz = pos;
      free_with_check(this->pages; this->pages = nullptr);
      free_with_check(ai);

      //
      MatCreateSeqAIJ(PETSC_COMM_SELF, this->size, this->size, 0, nnz_array, &matrix);
      //  MatSetOption(matrix, MAT_ROW_ORIENTED);
      //  MatSetOption(matrix, MAT_ROWS_SORTED);
      free_with_check(nnz_array);

      inited = true;
    }
Exemple #4
0
 void Filter<Scalar>::free()
 {
   if (unimesh)
   {
     for (int i = 0; i < num; i++)
       free_with_check(unidata[i]);
     free_with_check(unidata);
   }
 }
Exemple #5
0
 Vector<Scalar>* PetscVector<Scalar>::change_sign()
 {
   PetscScalar* y = malloc_with_check(this->size, this);
   int *idx = malloc_with_check(this->size, this);
   for (unsigned int i = 0; i < this->size; i++) idx[i] = i;
   VecGetValues(vec, this->size, idx, y);
   for (unsigned int i = 0; i < this->size; i++) y[i] *= -1.;
   VecSetValues(vec, this->size, idx, y, INSERT_VALUES);
   free_with_check(y);
   free_with_check(idx);
   return this;
 }
    void NonlinearMatrixSolver<Scalar>::init_solving(Scalar* coeff_vec)
    {
      this->check();
      this->tick();

      // Number of DOFs.
      assert(this->problem_size > 0);

      free_with_check(this->sln_vector, true);
      this->sln_vector = malloc_with_check<NonlinearMatrixSolver<Scalar>, Scalar>(this->problem_size, this, true);

      if (coeff_vec == nullptr)
        memset(this->sln_vector, 0, this->problem_size*sizeof(Scalar));
      else
        memcpy(this->sln_vector, coeff_vec, this->problem_size*sizeof(Scalar));

      // previous_sln_vector
      this->previous_sln_vector = calloc_with_check<NonlinearMatrixSolver<Scalar>, Scalar>(this->problem_size, this, true);

      // Backup vector for unsuccessful reuse of Jacobian.
      residual_back = create_vector<Scalar>();
      residual_back->alloc(this->problem_size);

      this->previous_jacobian = nullptr;
      this->previous_residual = nullptr;

      this->on_initialization();
    }
Exemple #7
0
    void OGProjectionNOX<Scalar>::project_global(SpaceSharedPtr<Scalar> space,
      MeshFunctionSharedPtr<Scalar> source_sln, MeshFunctionSharedPtr<Scalar> target_sln,
      NormType proj_norm,
      double newton_tol, int newton_max_iter)
    {
      if(proj_norm == HERMES_UNSET_NORM)
      {
        SpaceType space_type = space->get_type();
        switch (space_type)
        {
        case HERMES_H1_SPACE: proj_norm = HERMES_H1_NORM; break;
        case HERMES_HCURL_SPACE: proj_norm = HERMES_HCURL_NORM; break;
        case HERMES_HDIV_SPACE: proj_norm = HERMES_HDIV_NORM; break;
        case HERMES_L2_SPACE: proj_norm = HERMES_L2_NORM; break;
        case HERMES_L2_MARKERWISE_CONST_SPACE: proj_norm = HERMES_L2_NORM; break;
        default: throw Hermes::Exceptions::Exception("Unknown space type in OGProjectionNOX<Scalar>::project_global().");
        }
      }

      // Calculate the coefficient vector.
      int ndof = space->get_num_dofs();
      Scalar* target_vec = malloc_with_check<Scalar>(ndof);
      project_global(space, source_sln, target_vec, proj_norm, newton_tol, newton_max_iter);

      // Translate coefficient vector into a Solution.
      Solution<Scalar>::vector_to_solution(target_vec, space, target_sln);

      // Clean up.
      free_with_check(target_vec);
    }
Exemple #8
0
 void PetscVector<Scalar>::extract(Scalar *v) const
 {
   int *idx = malloc_with_check(this->size, this);
   for (unsigned int i = 0; i < this->size; i++) idx[i] = i;
   vec_get_value(vec, this->size, idx, v);
   free_with_check(idx);
 }
Exemple #9
0
    void CSMatrix<Scalar>::alloc()
    {
      assert(this->pages != nullptr);

      // initialize the arrays Ap and Ai
      Ap = malloc_with_check<CSMatrix<Scalar>, int>(this->size + 1, this);
      int aisize = this->get_num_indices();
      Ai = malloc_with_check<CSMatrix<Scalar>, int>(aisize, this);

      // sort the indices and remove duplicities, insert into Ai
      unsigned int i;
      int pos = 0;
      for (i = 0; i < this->size; i++)
      {
        Ap[i] = pos;
        pos += this->sort_and_store_indices(this->pages[i], Ai + pos, Ai + aisize);
      }
      Ap[i] = pos;

      free_with_check(this->pages);
      this->pages = nullptr;

      nnz = Ap[this->size];

      this->alloc_data();
    }
Exemple #10
0
    void OGProjectionNOX<Scalar>::project_internal(SpaceSharedPtr<Scalar> space, WeakForm<Scalar>* wf,
      Scalar* target_vec, double newton_tol, int newton_max_iter)
    {
        // Sanity check.
        if(space == nullptr)
          throw Hermes::Exceptions::Exception("this->space == nullptr in project_internal().");

      // Get dimension of the space.
      int ndof = space->get_num_dofs();

      // Initialize DiscreteProblem.
      DiscreteProblemNOX<Scalar> dp(wf, space);

      // Initial coefficient vector for the Newton's method.
      Scalar* coeff_vec = calloc_with_check<Scalar>(ndof);

      const char* iterative_method = "GMRES";           // Name of the iterative method employed by AztecOO (ignored
      // by the other solvers).
      // Possibilities: gmres, cg, cgs, tfqmr, bicgstab.
      const char* preconditioner = "New Ifpack";           // Name of the preconditioner employed by AztecOO
      // Possibilities: None" - No preconditioning.
      // "AztecOO" - AztecOO internal preconditioner.
      // "new_ Ifpack" - Ifpack internal preconditioner.
      // "ML" - Multi level preconditione
      unsigned message_type = NOX::Utils::Error | NOX::Utils::Warning | NOX::Utils::OuterIteration | NOX::Utils::InnerIteration | NOX::Utils::Parameters | NOX::Utils::LinearSolverDetails;
      // NOX error messages, see NOX_Utils.h.
      double ls_tolerance = 1e-5;                       // Tolerance for linear system.
      unsigned flag_absresid = 0;                       // Flag for absolute value of the residuum.
      double abs_resid = 1.0e-3;                        // Tolerance for absolute value of the residuum.
      unsigned flag_relresid = 1;                       // Flag for relative value of the residuum.
      double rel_resid = newton_tol;                        // Tolerance for relative value of the residuum.
      int max_iters = newton_max_iter;                  // Max number of iterations.

      // Initialize NOX.
      NewtonSolverNOX<Scalar> newton_nox(&dp);

      // Set NOX parameters.
      newton_nox.set_verbose_output(false);
      newton_nox.set_output_flags(message_type);
      newton_nox.set_ls_type(iterative_method);
      newton_nox.set_ls_tolerance(ls_tolerance);
      newton_nox.set_conv_iters(max_iters);
      if(flag_absresid)
        newton_nox.set_conv_abs_resid(abs_resid);
      if(flag_relresid)
        newton_nox.set_conv_rel_resid(rel_resid);
      newton_nox.set_precond(preconditioner);
      newton_nox.set_precond_reuse("Rebuild");

      // Perform Newton's iteration via NOX
      newton_nox.solve(coeff_vec);

      free_with_check(coeff_vec);

      if(target_vec != nullptr)
        for (int i = 0; i < ndof; i++)
          target_vec[i] = newton_nox.get_sln_vector()[i];
    }
    void DiscreteProblemFormAssembler<Scalar>::assemble_vector_form(VectorForm<Scalar>* form, int order, Func<double>** test_fns, Func<Scalar>** ext, Func<Scalar>** u_ext, 
      AsmList<Scalar>* current_als_i, Traverse::State* current_state, int n_quadrature_points, Geom<double>* geometry, double* jacobian_x_weights)
    {
      bool surface_form = (dynamic_cast<VectorFormVol<Scalar>*>(form) == nullptr);

      Func<Scalar>** local_ext = ext;

      // If the user supplied custom ext functions for this form.
      if(form->ext.size() > 0)
      {
        int local_ext_count = form->ext.size();
        local_ext = malloc_with_check(local_ext_count, this);
        for(int ext_i = 0; ext_i < local_ext_count; ext_i++)
          if(form->ext[ext_i])
            local_ext[ext_i] = init_fn(form->ext[ext_i].get(), order);
          else
            local_ext[ext_i] = nullptr;
      }

      // Account for the previous time level solution previously inserted at the back of ext.
      if(rungeKutta)
        u_ext += form->u_ext_offset;

      // Actual form-specific calculation.
      for (unsigned int i = 0; i < current_als_i->cnt; i++)
      {
        if(current_als_i->dof[i] < 0)
          continue;

        // Is this necessary, i.e. is there a coefficient smaller than Hermes::HermesSqrtEpsilon?
        if(std::abs(current_als_i->coef[i]) < Hermes::HermesSqrtEpsilon)
          continue;

        Func<double>* v = test_fns[i];

        Scalar val;
        if(surface_form)
          val = 0.5 * form->value(n_quadrature_points, jacobian_x_weights, u_ext, v, geometry, local_ext) * form->scaling_factor * current_als_i->coef[i];
        else
          val = form->value(n_quadrature_points, jacobian_x_weights, u_ext, v, geometry, local_ext) * form->scaling_factor * current_als_i->coef[i];

        current_rhs->add(current_als_i->dof[i], val);
      }

      if(form->ext.size() > 0)
      {
        for(int ext_i = 0; ext_i < form->ext.size(); ext_i++)
          if(form->ext[ext_i])
          {
            local_ext[ext_i]->free_fn();
            delete local_ext[ext_i];
          }
          free_with_check(local_ext);
      }

      if(rungeKutta)
        u_ext -= form->u_ext_offset;
    }
Exemple #12
0
 void EpetraMatrix<Scalar>::extract_row_copy(unsigned int row, unsigned int len, unsigned int &n_entries, double *vals, unsigned int *idxs)
 {
   int* idxs_to_pass = malloc_with_check(len, this);
   for (unsigned int i = 0; i < len; i++)
     idxs_to_pass[i] = idxs[i];
   int n_entries_to_pass = n_entries;
   mat->ExtractGlobalRowCopy(row, len, n_entries_to_pass, vals, idxs_to_pass);
   free_with_check(idxs_to_pass);
 }
 void NonlinearMatrixSolver<Scalar>::deinit_solving()
 {
   free_with_check(this->previous_sln_vector, true);
   delete residual_back;
   this->problem_size = -1;
   if (this->previous_jacobian)
     delete this->previous_jacobian;
   if (this->previous_residual)
     delete this->previous_residual;
 }
Exemple #14
0
 void SparseMatrix<Scalar>::free()
 {
   if (pages)
   {
     for (unsigned int i = 0; i < this->size; i++)
     if (pages[i])
       delete pages[i];
     free_with_check(pages);
   }
 }
Exemple #15
0
      void MatrixRhsOutput<Scalar>::process_vector_output(Hermes::Algebra::Vector<Scalar>* rhs)
      {
        if (rhs == nullptr)
          return;

        if (this->output_rhsOn)
        {
          char* fileName = malloc_with_check<char>(this->RhsFilename.length() + 5);
          sprintf(fileName, "%s", this->RhsFilename.c_str());
          rhs->export_to_file(fileName, this->RhsVarname.c_str(), this->RhsFormat, this->rhs_number_format);
          free_with_check(fileName);
        }
      }
Exemple #16
0
      void MatrixRhsOutput<Scalar>::process_matrix_output(Hermes::Algebra::SparseMatrix<Scalar>* matrix)
      {
        if (matrix == nullptr)
          return;

        if (this->output_matrixOn)
        {
          char* fileName = malloc_with_check<char>(this->matrixFilename.length() + 5);
          sprintf(fileName, "%s", this->matrixFilename.c_str());
          matrix->export_to_file(fileName, this->matrixVarname.c_str(), this->matrixFormat, this->matrix_number_format);
          free_with_check(fileName);
        }
      }
Exemple #17
0
      void MatrixRhsOutput<Scalar>::process_vector_output(Hermes::Algebra::Vector<Scalar>* rhs, int iteration)
      {
        if (rhs == nullptr)
          return;

        if (this->output_rhsOn)
        {
          char* fileName = malloc_with_check<char>(this->RhsFilename.length() + 5);
          if (this->only_lastRhsIteration)
            sprintf(fileName, "%s", this->RhsFilename.c_str());
          else if (this->output_rhsIterations == -1 || this->output_rhsIterations >= iteration)
            sprintf(fileName, "%s_%i", this->RhsFilename.c_str(), iteration);
          else
          {
            free_with_check(fileName);
            return;
          }

          rhs->export_to_file(fileName, this->RhsVarname.c_str(), this->RhsFormat, this->rhs_number_format);
          free_with_check(fileName);
        }
      }
Exemple #18
0
      void MatrixRhsOutput<Scalar>::process_matrix_output(Hermes::Algebra::SparseMatrix<Scalar>* matrix, int iteration)
      {
        if (matrix == nullptr)
          return;

        if (this->output_matrixOn)
        {
          char* fileName = malloc_with_check<char>(this->matrixFilename.length() + 5);
          if (this->only_lastMatrixIteration)
            sprintf(fileName, "%s", this->matrixFilename.c_str());
          else if (this->output_matrixIterations == -1 || this->output_matrixIterations >= iteration)
            sprintf(fileName, "%s_%i", this->matrixFilename.c_str(), iteration);
          else
          {
            free_with_check(fileName);
            return;
          }

          matrix->export_to_file(fileName, this->matrixVarname.c_str(), this->matrixFormat, this->matrix_number_format);
          free_with_check(fileName);
        }
      }
    void UMFPackLinearMatrixSolver<double>::solve()
    {
      assert(m != nullptr);
      assert(rhs != nullptr);
      assert(m->get_size() == rhs->get_size());

      this->tick();

      if (!setup_factorization())
        throw Exceptions::LinearMatrixSolverException("LU factorization could not be completed.");

      free_with_check(sln);

      sln = calloc_with_check<UMFPackLinearMatrixSolver<double>, double>(m->get_size(), this);
      int status = umfpack_real_solve(UMFPACK_A, m->get_Ap(), m->get_Ai(), m->get_Ax(), sln, rhs->v, numeric, nullptr, nullptr);
      if (status != UMFPACK_OK)
      {
        this->free_factorization_data();
        throw Exceptions::LinearMatrixSolverException(check_status("UMFPACK solution", status));
      }

      this->tick();
    }
    void UMFPackLinearMatrixSolver<std::complex<double> >::solve()
    {
      assert(m != nullptr);
      assert(rhs != nullptr);
      assert(m->get_size() == rhs->get_size());

      this->tick();
      if (!setup_factorization())
        this->warn("LU factorization could not be completed.");

      free_with_check(sln);
      sln = malloc_with_check<UMFPackLinearMatrixSolver<std::complex<double> >, std::complex<double> >(m->get_size(), this);

      memset(sln, 0, m->get_size() * sizeof(std::complex<double>));
      int status = umfpack_complex_solve(UMFPACK_A, m->get_Ap(), m->get_Ai(), (double *)m->get_Ax(), nullptr, (double*)sln, nullptr, (double *)rhs->v, nullptr, numeric, nullptr, nullptr);
      if (status != UMFPACK_OK)
      {
        this->free_factorization_data();
        throw Exceptions::LinearMatrixSolverException(check_status("UMFPACK solution", status));
      }

      this->tick();
      time = this->accumulated();
    }
 void NonlinearMatrixSolver<Scalar>::free()
 {
   free_with_check(this->sln_vector, true);
 }
Exemple #22
0
    void SimpleVector<Scalar>::export_to_file(const char *filename, const char *var_name, MatrixExportFormat fmt, char* number_format)
    {
      if (!v)
        throw Exceptions::MethodNotOverridenException("Vector<Scalar>::export_to_file");

      switch (fmt)
      {
      case EXPORT_FORMAT_MATRIX_MARKET:
      {
        FILE* file = fopen(filename, "w");
        if (!file)
          throw Exceptions::IOException(Exceptions::IOException::Write, filename);
        if (Hermes::Helpers::TypeIsReal<Scalar>::value)
          fprintf(file, "%%%%MatrixMarket matrix coordinate real general\n");
        else
          fprintf(file, "%%%%MatrixMarket matrix coordinate complex general\n");

        fprintf(file, "%d 1 %d\n", this->size, this->size);

        for (unsigned int j = 0; j < this->size; j++)
        {
          Hermes::Helpers::fprint_coordinate_num(file, j + 1, 1, v[j], number_format);
          fprintf(file, "\n");
        }

        fclose(file);
      }
        break;

      case EXPORT_FORMAT_MATLAB_MATIO:
      {
#ifdef WITH_MATIO
        size_t dims[2];
        dims[0] = this->size;
        dims[1] = 1;

        mat_t *mat = Mat_CreateVer(filename, "", MAT_FT_MAT5);
        matvar_t *matvar;

        // For complex.
        double* v_re = nullptr;
        double* v_im = nullptr;

        void* data;
        if (Hermes::Helpers::TypeIsReal<Scalar>::value)
        {
          data = v;
          matvar = Mat_VarCreate(var_name, MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, data, MAT_F_DONT_COPY_DATA);
        }
        else
        {
          v_re = malloc_with_check<SimpleVector<Scalar>, double>(this->size, this);
          v_im = malloc_with_check<SimpleVector<Scalar>, double>(this->size, this);
          struct mat_complex_split_t z = { v_re, v_im };

          for (int i = 0; i < this->size; i++)
          {
            v_re[i] = ((std::complex<double>)(this->v[i])).real();
            v_im[i] = ((std::complex<double>)(this->v[i])).imag();
            data = &z;
          }
          matvar = Mat_VarCreate(var_name, MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, data, MAT_F_DONT_COPY_DATA | MAT_F_COMPLEX);
        }

        if (matvar)
        {
          Mat_VarWrite(mat, matvar, MAT_COMPRESSION_ZLIB);
          Mat_VarFree(matvar);
        }

        free_with_check(v_re);
        free_with_check(v_im);
        Mat_Close(mat);

        if (!matvar)
          throw Exceptions::IOException(Exceptions::IOException::Write, filename);
#else
        throw Exceptions::Exception("MATIO not included.");
#endif
      }
        break;

      case EXPORT_FORMAT_PLAIN_ASCII:
      case EXPORT_FORMAT_MATLAB_SIMPLE:
      {
        FILE* file = fopen(filename, "w");
        if (!file)
          throw Exceptions::IOException(Exceptions::IOException::Write, filename);
        for (unsigned int i = 0; i < this->size; i++)
        {
          Hermes::Helpers::fprint_num(file, v[i], number_format);
          fprintf(file, "\n");
        }
        fclose(file);
      }
        break;

#ifdef WITH_BSON
      case EXPORT_FORMAT_BSON:
      {
        // Init bson
        bson bw;
        bson_init(&bw);

        // Matrix size.
        bson_append_int(&bw, "size", this->size);

        bson_append_start_array(&bw, "v");
        for (unsigned int i = 0; i < this->size; i++)
          bson_append_double(&bw, "v_i", real(this->v[i]));
        bson_append_finish_array(&bw);

        if (!Hermes::Helpers::TypeIsReal<Scalar>::value)
        {
          bson_append_start_array(&bw, "v-imag");
          for (unsigned int i = 0; i < this->size; i++)
            bson_append_double(&bw, "v_i", imag(this->v[i]));
          bson_append_finish_array(&bw);
        }

        // Done.
        bson_finish(&bw);

        // Write to disk.
        FILE *fpw;
        fpw = fopen(filename, "wb");
        const char *dataw = (const char *)bson_data(&bw);
        fwrite(dataw, bson_size(&bw), 1, fpw);
        fclose(fpw);

        bson_destroy(&bw);
      }
#endif
      }
    }
Exemple #23
0
    void CSMatrix<Scalar>::export_to_file(const char *filename, const char *var_name, MatrixExportFormat fmt, char* number_format, bool invert_storage)
    {
      switch (fmt)
      {
      case EXPORT_FORMAT_MATRIX_MARKET:
      {
                                        FILE* file = fopen(filename, "w");
                                        if (!file)
                                          throw Exceptions::IOException(Exceptions::IOException::Write, filename);
                                        if (Hermes::Helpers::TypeIsReal<Scalar>::value)
                                          fprintf(file, "%%%%MatrixMarket matrix coordinate real general\n");
                                        else
                                          fprintf(file, "%%%%MatrixMarket matrix coordinate complex general\n");

                                        fprintf(file, "%d %d %d\n", this->size, this->size, this->nnz);

                                        if (invert_storage)
                                          this->switch_orientation();
                                        for (unsigned int j = 0; j < this->size; j++)
                                        {
                                          for (int i = Ap[j]; i < Ap[j + 1]; i++)
                                          {
                                            Hermes::Helpers::fprint_coordinate_num(file, i_coordinate(Ai[i] + 1, j + 1, invert_storage), j_coordinate(Ai[i] + 1, j + 1, invert_storage), Ax[i], number_format);
                                            fprintf(file, "\n");
                                          }
                                        }
                                        if (invert_storage)
                                          this->switch_orientation();

                                        fclose(file);
      }
        break;

      case EXPORT_FORMAT_MATLAB_MATIO:
      {
#ifdef WITH_MATIO
                                       mat_sparse_t sparse;
                                       sparse.nzmax = this->nnz;
                                       if (invert_storage)
                                         this->switch_orientation();

                                       sparse.nir = this->nnz;
                                       sparse.ir = Ai;
                                       sparse.njc = this->size + 1;
                                       sparse.jc = (int *)Ap;
                                       sparse.ndata = this->nnz;

                                       size_t dims[2];
                                       dims[0] = this->size;
                                       dims[1] = this->size;

                                       mat_t *mat = Mat_CreateVer(filename, "", MAT_FT_MAT5);

                                       matvar_t *matvar;

                                       // For complex. No allocation here.
                                       double* Ax_re = nullptr;
                                       double* Ax_im = nullptr;

                                       // For real.
                                       if (Hermes::Helpers::TypeIsReal<Scalar>::value)
                                       {
                                         sparse.data = Ax;
                                         matvar = Mat_VarCreate(var_name, MAT_C_SPARSE, MAT_T_DOUBLE, 2, dims, &sparse, MAT_F_DONT_COPY_DATA);
                                       }
                                       else
                                       {
                                         // For complex.
                                         Ax_re = malloc_with_check<CSMatrix<Scalar>, double>(this->nnz, this);
                                         Ax_im = malloc_with_check<CSMatrix<Scalar>, double>(this->nnz, this);
                                         struct mat_complex_split_t z = { Ax_re, Ax_im };

                                         for (int i = 0; i < this->nnz; i++)
                                         {
                                           Ax_re[i] = ((std::complex<double>)(this->Ax[i])).real();
                                           Ax_im[i] = ((std::complex<double>)(this->Ax[i])).imag();
                                           sparse.data = &z;
                                         }
                                         matvar = Mat_VarCreate(var_name, MAT_C_SPARSE, MAT_T_DOUBLE, 2, dims, &sparse, MAT_F_DONT_COPY_DATA | MAT_F_COMPLEX);
                                       }

                                       if (matvar)
                                       {
                                         Mat_VarWrite(mat, matvar, MAT_COMPRESSION_ZLIB);
                                         Mat_VarFree(matvar);
                                       }
                                       if (invert_storage)
                                         this->switch_orientation();
                                       free_with_check(Ax_re);
                                       free_with_check(Ax_im);
                                       Mat_Close(mat);

                                       if (!matvar)
                                         throw Exceptions::IOException(Exceptions::IOException::Write, filename);
#endif
      }
        break;

      case EXPORT_FORMAT_PLAIN_ASCII:
      {
                                      FILE* file = fopen(filename, "w");
                                      if (!file)
                                        throw Exceptions::IOException(Exceptions::IOException::Write, filename);

                                      if (invert_storage)
                                        this->switch_orientation();
                                      for (unsigned int j = 0; j < this->size; j++)
                                      {
                                        for (int i = Ap[j]; i < Ap[j + 1]; i++)
                                        {
                                          Helpers::fprint_coordinate_num(file, i_coordinate(Ai[i], j, invert_storage), j_coordinate(Ai[i], j, invert_storage), Ax[i], number_format);
                                          fprintf(file, "\n");
                                        }
                                      }
                                      if (invert_storage)
                                        this->switch_orientation();

                                      fclose(file);
      }
        break;
#ifdef WITH_BSON
      case EXPORT_FORMAT_BSON:
      {
        // Init bson
        bson bw;
        bson_init(&bw);

        // Matrix size.
        bson_append_int(&bw, "size", this->size);
        // Nonzeros.
        bson_append_int(&bw, "nnz", this->nnz);

        if (invert_storage)
          this->switch_orientation();

        bson_append_start_array(&bw, "Ap");
        for (unsigned int i = 0; i < this->size; i++)
          bson_append_int(&bw, "p", this->Ap[i]);
        bson_append_finish_array(&bw);

        bson_append_start_array(&bw, "Ai");
        for (unsigned int i = 0; i < this->nnz; i++)
          bson_append_int(&bw, "i", this->Ai[i]);
        bson_append_finish_array(&bw);

        bson_append_start_array(&bw, "Ax");
        for (unsigned int i = 0; i < this->nnz; i++)
          bson_append_double(&bw, "x", real(this->Ax[i]));
        bson_append_finish_array(&bw);

        if (!Hermes::Helpers::TypeIsReal<Scalar>::value)
        {
          bson_append_start_array(&bw, "Ax-imag");
          for (unsigned int i = 0; i < this->nnz; i++)
            bson_append_double(&bw, "x-i", imag(this->Ax[i]));
          bson_append_finish_array(&bw);
        }
        bson_append_finish_array(&bw);

        if (invert_storage)
          this->switch_orientation();

        // Done.
        bson_finish(&bw);

        // Write to disk.
        FILE *fpw;
        fpw = fopen(filename, "wb");
        const char *dataw = (const char *)bson_data(&bw);
        fwrite(dataw, bson_size(&bw), 1, fpw);
        fclose(fpw);

        bson_destroy(&bw);
      }
        break;
#endif
      }
    }
    void DiscreteProblemFormAssembler<Scalar>::assemble_matrix_form(MatrixForm<double, Scalar>* form, int order, Func<double>** base_fns, Func<double>** test_fns, Func<Scalar>** ext, Func<Scalar>** u_ext,
      AsmList<Scalar>* current_als_i, AsmList<Scalar>* current_als_j, Traverse::State* current_state, int n_quadrature_points, Geom<double>* geometry, double* jacobian_x_weights)
    {
      bool surface_form = (dynamic_cast<MatrixFormVol<Scalar>*>(form) == nullptr);

      double block_scaling_coefficient = this->block_scaling_coeff(form);

      bool tra = (form->i != form->j) && (form->sym != 0);
      bool sym = (form->i == form->j) && (form->sym == 1);

      // Assemble the local stiffness matrix for the form form.
      Scalar **local_stiffness_matrix = new_matrix<Scalar>(std::max(current_als_i->cnt, current_als_j->cnt));

      Func<Scalar>** local_ext = ext;
      // If the user supplied custom ext functions for this form.
      if(form->ext.size() > 0)
      {
        int local_ext_count = form->ext.size();
        local_ext = malloc_with_check(local_ext_count, this);
        for(int ext_i = 0; ext_i < local_ext_count; ext_i++)
          if(form->ext[ext_i])
            local_ext[ext_i] = current_state->e[ext_i] == nullptr ? nullptr : init_fn(form->ext[ext_i].get(), order);
          else
            local_ext[ext_i] = nullptr;
      }

      // Account for the previous time level solution previously inserted at the back of ext.
      if(rungeKutta)
        u_ext += form->u_ext_offset;

      // Actual form-specific calculation.
      for (unsigned int i = 0; i < current_als_i->cnt; i++)
      {
        if(current_als_i->dof[i] < 0)
          continue;

        if((!tra || surface_form) && current_als_i->dof[i] < 0)
          continue;
        if(std::abs(current_als_i->coef[i]) < Hermes::HermesSqrtEpsilon)
          continue;
        if(!sym)
        {
          for (unsigned int j = 0; j < current_als_j->cnt; j++)
          {
            if(current_als_j->dof[j] >= 0)
            {
              // Is this necessary, i.e. is there a coefficient smaller than Hermes::HermesSqrtEpsilon?
              if(std::abs(current_als_j->coef[j]) < Hermes::HermesSqrtEpsilon)
                continue;

              Func<double>* u = base_fns[j];
              Func<double>* v = test_fns[i];

              if(surface_form)
                local_stiffness_matrix[i][j] = 0.5 * block_scaling_coefficient * form->value(n_quadrature_points, jacobian_x_weights, u_ext, u, v, geometry, local_ext) * form->scaling_factor * current_als_j->coef[j] * current_als_i->coef[i];
              else
                local_stiffness_matrix[i][j] = block_scaling_coefficient * form->value(n_quadrature_points, jacobian_x_weights, u_ext, u, v, geometry, local_ext) * form->scaling_factor * current_als_j->coef[j] * current_als_i->coef[i];
            }
          }
        }
        // Symmetric block.
        else
        {
          for (unsigned int j = 0; j < current_als_j->cnt; j++)
          {
            if(j < i && current_als_j->dof[j] >= 0)
              continue;
            if(current_als_j->dof[j] >= 0)
            {
              // Is this necessary, i.e. is there a coefficient smaller than Hermes::HermesSqrtEpsilon?
              if(std::abs(current_als_j->coef[j]) < Hermes::HermesSqrtEpsilon)
                continue;

              Func<double>* u = base_fns[j];
              Func<double>* v = test_fns[i];

              Scalar val = block_scaling_coefficient * form->value(n_quadrature_points, jacobian_x_weights, u_ext, u, v, geometry, local_ext) * form->scaling_factor * current_als_j->coef[j] * current_als_i->coef[i];

              local_stiffness_matrix[i][j] = local_stiffness_matrix[j][i] = val;
            }
          }
        }
      }

      // Insert the local stiffness matrix into the global one.
      current_mat->add(current_als_i->cnt, current_als_j->cnt, local_stiffness_matrix, current_als_i->dof, current_als_j->dof);

      // Insert also the off-diagonal (anti-)symmetric block, if required.
      if(tra)
      {
        if(form->sym < 0)
          chsgn(local_stiffness_matrix, current_als_i->cnt, current_als_j->cnt);
        transpose(local_stiffness_matrix, current_als_i->cnt, current_als_j->cnt);

        current_mat->add(current_als_j->cnt, current_als_i->cnt, local_stiffness_matrix, current_als_j->dof, current_als_i->dof);
      }

      if(form->ext.size() > 0)
      {
        for(int ext_i = 0; ext_i < form->ext.size(); ext_i++)
          if(form->ext[ext_i])
          {
            local_ext[ext_i]->free_fn();
            delete local_ext[ext_i];
          }
          free_with_check(local_ext);
      }

      if(rungeKutta)
        u_ext -= form->u_ext_offset;

      // Cleanup.
      free_with_check(local_stiffness_matrix);
    }
Exemple #25
0
    void GnuplotGraph::save(const char* filename)
    {
      int j;

      if (!rows.size()) throw Hermes::Exceptions::Exception("No data rows defined.");

      FILE* f = fopen(filename, "w");
      if (f == nullptr) throw Hermes::Exceptions::Exception("Error writing to %s", filename);

      fprintf(f, "%s", terminal_str.c_str());

      int len = strlen(filename);
      char* outname = malloc_with_check<char>(len + 10);
      strcpy(outname, filename);
      char* slash = strrchr(outname, '/');
      if (slash != nullptr) strcpy(outname, ++slash);
      char* dot = strrchr(outname, '.');
      if (dot != nullptr && dot > outname) *dot = 0;
      strcat(outname, ".eps");

      fprintf(f, "set output '%s'\n", (char*)outname);
      free_with_check(outname);

      fprintf(f, "set size 0.8, 0.8\n");

      if (logx && !logy)
        fprintf(f, "set logscale x\n");
      else if (!logx && logy)
        fprintf(f, "set logscale y\n");
      else if (logx && logy)
      {
        fprintf(f, "set logscale x\n");
        fprintf(f, "set logscale y\n");
      }

      if (grid) fprintf(f, "set grid\n");

      if (title.length()) fprintf(f, "set title '%s'\n", title.c_str());
      if (xname.length()) fprintf(f, "set xlabel '%s'\n", xname.c_str());
      if (yname.length()) fprintf(f, "set ylabel '%s'\n", yname.c_str());
      if (legend && legend_pos.length()) fprintf(f, "set key %s\n", legend_pos.c_str());

      fprintf(f, "plot");
      for (unsigned int i = 0; i < rows.size(); i++)
      {
        int ct, lt, pt;
        get_style_types(rows[i].line, rows[i].marker, rows[i].color, lt, pt, ct);

        if (lt == 0)
          fprintf(f, " '-' w p pointtype %d", pt);
        else if (ct < 0)
          fprintf(f, " '-' w lp linewidth %g linetype %d pointtype %d", this->lw, lt, pt);
        else
          fprintf(f, " '-' w lp linewidth %g linecolor %d linetype %d pointtype %d", this->lw, ct, lt, pt);

        if (legend)
          fprintf(f, " title '%s' ", rows[i].name.c_str());
        else
          fprintf(f, " notitle ");

        if (i < rows.size() - 1) fprintf(f, ",\\\n     ");
      }
      fprintf(f, "\n");

      for (unsigned int i = 0; i < rows.size(); i++)
      {
        int rsize = rows[i].data.size();
        for (j = 0; j < rsize; j++)
          fprintf(f, "%.14g  %.14g\n", rows[i].data[j].x, rows[i].data[j].y);
        fprintf(f, "e\n");
      }

      fprintf(f, "set terminal x11\n");
      fclose(f);

      this->info("Graph saved. Process the file '%s' with gnuplot.", filename);
    }
Exemple #26
0
    void SimpleVector<Scalar>::import_from_file(const char *filename, const char *var_name, MatrixExportFormat fmt)
    {
      switch (fmt)
      {
      case EXPORT_FORMAT_PLAIN_ASCII:
      {
        std::vector<Scalar> data;
        std::ifstream input(filename);
        if (input.bad())
          throw Exceptions::IOException(Exceptions::IOException::Read, filename);
        std::string lineData;

        while (getline(input, lineData))
        {
          Scalar d;
          std::stringstream lineStream(lineData);
          lineStream >> d;
          data.push_back(d);
        }

        this->alloc(data.size());
        memcpy(this->v, &data[0], sizeof(Scalar)*data.size());
      }
        break;
      case EXPORT_FORMAT_MATLAB_MATIO:
#ifdef WITH_MATIO
        mat_t    *matfp;
        matvar_t *matvar;

        matfp = Mat_Open(filename, MAT_ACC_RDONLY);

        if (!matfp)
        {
          throw Exceptions::IOException(Exceptions::IOException::Read, filename);
          return;
        }

        matvar = Mat_VarRead(matfp, var_name);
        if (matvar)
        {
          this->alloc(matvar->dims[0]);
          if (Hermes::Helpers::TypeIsReal<Scalar>::value)
            memcpy(this->v, matvar->data, sizeof(Scalar)*this->size);
          else
          {
            std::complex<double>* complex_data = malloc_with_check<SimpleVector<Scalar>, std::complex<double> >(this->size, this);
            double* real_array = (double*)((mat_complex_split_t*)matvar->data)->Re;
            double* imag_array = (double*)((mat_complex_split_t*)matvar->data)->Im;
            for (int i = 0; i < this->size; i++)
              complex_data[i] = std::complex<double>(real_array[i], imag_array[i]);
            memcpy(this->v, complex_data, sizeof(Scalar)*this->size);
            free_with_check(complex_data);
          }
        }

        Mat_Close(matfp);
        if (!matvar)
          throw Exceptions::IOException(Exceptions::IOException::Read, filename);
#else
        throw Exceptions::Exception("MATIO not included.");
#endif
        break;
      case EXPORT_FORMAT_MATRIX_MARKET:
        throw Hermes::Exceptions::MethodNotImplementedException("SimpleVector<Scalar>::import_from_file - Matrix Market");
        break;
#ifdef WITH_BSON
      case EXPORT_FORMAT_BSON:
      {
        FILE *fpr;
        fpr = fopen(filename, "rb");

        // file size:
        fseek(fpr, 0, SEEK_END);
        int size = ftell(fpr);
        rewind(fpr);

        // allocate memory to contain the whole file:
        char *datar = malloc_with_check<char>(size);
        fread(datar, size, 1, fpr);
        fclose(fpr);

        bson br;
        bson_init_finished_data(&br, datar, 0);

        bson_iterator it;
        bson sub;
        bson_find(&it, &br, "size");
        this->size = bson_iterator_int(&it);

        this->v = malloc_with_check<SimpleVector<Scalar>, Scalar>(this->size, this);

        bson_iterator it_coeffs;
        bson_find(&it_coeffs, &br, "v");
        bson_iterator_subobject_init(&it_coeffs, &sub, 0);
        bson_iterator_init(&it, &sub);
        int index_coeff = 0;
        while (bson_iterator_next(&it))
          this->v[index_coeff++] = bson_iterator_double(&it);

        if (!Hermes::Helpers::TypeIsReal<Scalar>::value)
        {
          bson_find(&it_coeffs, &br, "v-imag");
          bson_iterator_subobject_init(&it_coeffs, &sub, 0);
          bson_iterator_init(&it, &sub);
          index_coeff = 0;
          while (bson_iterator_next(&it))
            ((std::complex<double>)this->v[index_coeff++]).imag(bson_iterator_double(&it));
        }

        bson_destroy(&br);
        free_with_check(datar);
      }
        break;
#endif
      }
    }
Exemple #27
0
      void OrderView::on_display()
      {
        set_ortho_projection();
        glDisable(GL_TEXTURE_1D);
        glDisable(GL_LIGHTING);
        glDisable(GL_DEPTH_TEST);

        // transform all vertices
        ord.lock_data();
        int i, nv = ord.get_num_vertices();
        double3* vert = ord.get_vertices();
        double2* tvert = malloc_with_check<double2>(nv);
        for (i = 0; i < nv; i++)
        {
          tvert[i][0] = transform_x(vert[i][0]);
          tvert[i][1] = transform_y(vert[i][1]);
        }

        // draw all triangles
        int3* tris = ord.get_triangles();
        glBegin(GL_TRIANGLES);
        for (i = 0; i < ord.get_num_triangles(); i++)
        {
          const float* color = order_colors[(int)vert[tris[i][0]][2]];
          glColor3f(color[0], color[1], color[2]);

          glVertex2d(tvert[tris[i][0]][0], tvert[tris[i][0]][1]);
          glVertex2d(tvert[tris[i][1]][0], tvert[tris[i][1]][1]);
          glVertex2d(tvert[tris[i][2]][0], tvert[tris[i][2]][1]);
        }
        glEnd();

        // draw all edges
        if (pal_type == 0)
          glColor3f(0.4f, 0.4f, 0.4f);
        else if (pal_type == 1)
          glColor3f(1.0f, 1.0f, 1.0f);
        else
          glColor3f(0.0f, 0.0f, 0.0f);
        glBegin(GL_LINES);
        int2* edges = ord.get_edges();
        for (i = 0; i < ord.get_num_edges(); i++)
        {
          glVertex2d(tvert[edges[i][0]][0], tvert[edges[i][0]][1]);
          glVertex2d(tvert[edges[i][1]][0], tvert[edges[i][1]][1]);
        }
        glEnd();

        // draw labels
        if (b_orders)
        {
          int* lvert;
          char** ltext;
          double2* lbox;
          int nl = ord.get_labels(lvert, ltext, lbox);
          for (i = 0; i < nl; i++)
          if (lbox[i][0] * scale > get_text_width(ltext[i]) &&
            lbox[i][1] * scale > 13)
          {
            //color = get_palette_color((vert[lvert[i]][2] - 1) / 9.0);
            const float* color = order_colors[(int)vert[lvert[i]][2]];
            if ((color[0] * 0.39f + color[1] * 0.50f + color[2] * 0.11f) > 0.5f)
              glColor3f(0, 0, 0);
            else
              glColor3f(1, 1, 1);

            draw_text(tvert[lvert[i]][0], tvert[lvert[i]][1], ltext[i], 0);
          }
        }

        free_with_check(tvert);
        ord.unlock_data();
      }
Exemple #28
0
    void CSMatrix<Scalar>::import_from_file(const char *filename, const char *var_name, MatrixExportFormat fmt, bool invert_storage)
    {
      this->free();

      switch (fmt)
      {
      case EXPORT_FORMAT_MATRIX_MARKET:
        throw Exceptions::MethodNotOverridenException("CSMatrix<Scalar>::import_from_file - Matrix Market");
        break;
      case EXPORT_FORMAT_MATLAB_MATIO:
      {
#ifdef WITH_MATIO
                                       mat_t    *matfp;
                                       matvar_t *matvar;

                                       matfp = Mat_Open(filename, MAT_ACC_RDONLY);

                                       if (!matfp)
                                         throw Exceptions::IOException(Exceptions::IOException::Read, filename);

                                       matvar = Mat_VarRead(matfp, var_name);

                                       if (matvar)
                                       {
                                         mat_sparse_t *sparse = (mat_sparse_t *)matvar->data;

                                         this->nnz = sparse->nir;
                                         this->Ax = malloc_with_check<CSMatrix<Scalar>, Scalar>(this->nnz, this);
                                         this->Ai = malloc_with_check<CSMatrix<Scalar>, int>(this->nnz, this);
                                         this->size = sparse->njc;
                                         this->Ap = malloc_with_check<CSMatrix<Scalar>, int>(this->size + 1, this);

                                         void* data = nullptr;
                                         if (Hermes::Helpers::TypeIsReal<Scalar>::value)
                                           data = sparse->data;
                                         else
                                         {
                                           std::complex<double>* complex_data = malloc_with_check<CSMatrix<Scalar>, std::complex<double> >(this->nnz, this);
                                           double* real_array = (double*)((mat_complex_split_t*)sparse->data)->Re;
                                           double* imag_array = (double*)((mat_complex_split_t*)sparse->data)->Im;
                                           for (int i = 0; i < this->nnz; i++)
                                             complex_data[i] = std::complex<double>(real_array[i], imag_array[i]);
                                           data = (void*)complex_data;
                                         }
                                         memcpy(this->Ax, data, this->nnz * sizeof(Scalar));
                                         if (!Hermes::Helpers::TypeIsReal<Scalar>::value)
                                           free_with_check(data);
                                         memcpy(this->Ap, sparse->jc, this->size * sizeof(int));
                                         this->Ap[this->size] = this->nnz;
                                         memcpy(this->Ai, sparse->ir, this->nnz * sizeof(int));

                                         if (invert_storage)
                                           this->switch_orientation();
                                       }

                                       Mat_Close(matfp);

                                       if (!matvar)
                                         throw Exceptions::IOException(Exceptions::IOException::Read, filename);
#else
                                       throw Exceptions::Exception("MATIO not included.");
#endif
      }
        break;

      case EXPORT_FORMAT_PLAIN_ASCII:
        throw Exceptions::MethodNotOverridenException("CSMatrix<Scalar>::import_from_file - Simple format");

#ifdef WITH_BSON
      case EXPORT_FORMAT_BSON:
      {
                               FILE *fpr;
                               fpr = fopen(filename, "rb");

                               // file size:
                               fseek(fpr, 0, SEEK_END);
                               int size = ftell(fpr);
                               rewind(fpr);

                               // allocate memory to contain the whole file:
                               char *datar = malloc_with_check<char>(size);
                               fread(datar, size, 1, fpr);
                               fclose(fpr);

                               bson br;
                               bson_init_finished_data(&br, datar, 0);

                               bson_iterator it;
                               bson sub;
                               bson_find(&it, &br, "size");
                               this->size = bson_iterator_int(&it);
                               bson_find(&it, &br, "nnz");
                               this->nnz = bson_iterator_int(&it);

                               this->Ap = malloc_with_check<CSMatrix<Scalar>, int>(this->size + 1, this);
                               this->Ai = malloc_with_check<CSMatrix<Scalar>, int>(nnz, this);
                               this->Ax = malloc_with_check<CSMatrix<Scalar>, Scalar>(nnz, this);

                               // coeffs
                               bson_iterator it_coeffs;
                               bson_find(&it_coeffs, &br, "Ap");
                               bson_iterator_subobject_init(&it_coeffs, &sub, 0);
                               bson_iterator_init(&it, &sub);
                               int index_coeff = 0;
                               while (bson_iterator_next(&it))
                                 this->Ap[index_coeff++] = bson_iterator_int(&it);
                               this->Ap[this->size] = this->nnz;

                               bson_find(&it_coeffs, &br, "Ai");
                               bson_iterator_subobject_init(&it_coeffs, &sub, 0);
                               bson_iterator_init(&it, &sub);
                               index_coeff = 0;
                               while (bson_iterator_next(&it))
                                 this->Ai[index_coeff++] = bson_iterator_int(&it);

                                bson_find(&it_coeffs, &br, "Ax");
                                bson_iterator_subobject_init(&it_coeffs, &sub, 0);
                                bson_iterator_init(&it, &sub);
                                index_coeff = 0;
                                while (bson_iterator_next(&it))
                                  this->Ax[index_coeff++] = bson_iterator_double(&it);
                               
                                if (!Hermes::Helpers::TypeIsReal<Scalar>::value)
                               {
                                 bson_find(&it_coeffs, &br, "Ax-imag");
                                 bson_iterator_subobject_init(&it_coeffs, &sub, 0);
                                 bson_iterator_init(&it, &sub);
                                 index_coeff = 0;
                                 while (bson_iterator_next(&it))
                                   ((std::complex<double>)this->Ax[index_coeff++]).imag(bson_iterator_double(&it));
                               }

                                if (invert_storage)
                                  this->switch_orientation();

                               bson_destroy(&br);
                               free_with_check(datar);
      }
#endif
        break;
      }
    }
Exemple #29
0
 void SimpleVector<Scalar>::free()
 {
   free_with_check(this->v);
   this->size = 0;
 }