Пример #1
0
void FreeMeshesAndDofVectors(struct StateData * state)
{
	free_dof_real_vec(state->massM_volume);
	free_dof_real_vec(state->massM_surface);
	free_dof_real_vec(state->massM_surface_on_vol);
	free_dof_real_vec(state->f_g_scalar_h_volume);
	free_dof_real_vec(state->g_x_scalar_h_volume);
	free_dof_real_vec(state->g_y_scalar_h_volume);
	free_dof_real_vec(state->f_h_volume);
	free_dof_real_vec(state->p_h_volume);
	free_dof_real_vec(state->p_volume);
	free_dof_real_vec(state->p_h_error_volume);
	free_dof_real_d_vec(state->vol_pos_t);
	free_dof_real_d_vec(state->grad_p_volume);
	free_dof_real_d_vec(state->f_h_surface);
	free_dof_real_d_vec(state->u_h_surface);
	free_dof_real_d_vec(state->u_h_surface_old);
	free_dof_real_d_vec(state->u_h_surface_t);
	free_dof_real_d_vec(state->surf_normals);
	free_dof_real_d_vec(state->grad_p_surface);
	free_dof_matrix(state->matrix_g_scalar_volume);
	free_dof_matrix(state->matrix_volume);
	free_dof_dowb_matrix(state->matrix_surface);
	free_dof_real_vec(state->coarsen_mark);
	free_dof_real_d_vec(state->deturck_originalPosition);
	free_dof_real_vec(state->deturck_Y[0]);
	free_dof_real_vec(state->deturck_Y[1]);
	free_dof_real_vec(state->deturck_Y[2]);
	free_dof_real_d_vec(state->deturck_zeta);
	free_dof_real_d_vec(state->deturck_HMinus1GradYSigma[0]);
	free_dof_real_d_vec(state->deturck_HMinus1GradYSigma[1]);
	free_dof_real_d_vec(state->deturck_HMinus1GradYSigma[2]);
	free_dof_real_d_vec(state->deturck_Um_1);
	free_dof_real_d_vec(state->deturck_T_eta);
	free_dof_real_vec(state->deturck_massDivisorsForVol);
	free_dof_int_vec(state->SurfaceToVolumeMap);
	free_dof_int_vec(state->VolumeToSurfaceMap);
	state->SurfaceToVolumeMap = nil;
	state->VolumeToSurfaceMap = nil;
	if(state->surfGradPDivisors != nil)
		free_dof_real_vec(state->surfGradPDivisors);
	state->surfGradPDivisors = nil;
	if(state->volGradPDivisors != nil)
		free_dof_real_vec(state->volGradPDivisors);
	state->volGradPDivisors = nil;

	free_mesh(state->volume_mesh);
	free_mesh(state->surface_mesh);
}
Пример #2
0
Файл: mesh.cpp Проект: tommp/V8
Mesh::~Mesh(){
	if (!free_mesh()) {
		std::cout << __FILE__ << ":" << __LINE__ << ": " << "FATAL ERROR: Failed to delete mesh buffers!" << std::endl;
		errorlogger("FATAL ERROR: Failed to delete mesh buffers!");
		exit(EXIT_FAILURE);
	}
}
Пример #3
0
int main()
{
  osh_init();
  struct mesh* m = new_box_mesh(2);
  mesh_derive_model(m, PI / 4);
  mesh_set_rep(m, MESH_FULL);
  char fname[64];
  unsigned it = 0;
  mesh_eval_field(m, 0, "adapt_size", 1, fine_fun);
  { //set mass field to test conservative transfer
    unsigned nelems = mesh_count(m, mesh_dim(m));
    mesh_add_tag(m, mesh_dim(m), TAG_F64, "mass", 1,
        doubles_filled(nelems, 1.0 / nelems));
  }
  while (refine_by_size(m, 0)) {
    sprintf(fname, "ref_%u.vtu", it++);
    write_mesh_vtk(m, fname);
    mesh_free_tag(m, 0, "adapt_size");
    mesh_eval_field(m, 0, "adapt_size", 1, fine_fun);
  }
  double minq = 0.1;
  printf("minq %f\n", minq);
  it = 0;
  mesh_free_tag(m, 0, "adapt_size");
  mesh_eval_field(m, 0, "adapt_size", 1, coarse_fun);
  while (coarsen_by_size(m, minq, 0.5)) {
    printf("%u elements\n", mesh_count(m, mesh_dim(m)));
    sprintf(fname, "cor_%u.vtu", it++);
    write_mesh_vtk(m, fname);
  }
  free_mesh(m);
  osh_fini();
}
Пример #4
0
int main(int argc, char** argv)
{
  comm_init();
  char const* path;
  if (argc == 2)
    path = argv[1];
  else
    path = ".";
  struct mesh* m = new_box_mesh(2);
  mesh_derive_model(m, PI / 4);
  mesh_set_rep(m, MESH_FULL);
  mesh_eval_field(m, 0, "adapt_size", 1, size_fun);
  while (refine_by_size(m, 0));
  char prefix[128];
  sprintf(prefix, "%s/warp", path);
  start_vtk_steps(prefix);
  mesh_eval_field(m, 0, "dye", 1, dye_fun);
  set_size_field(m);
  write_vtk_step(m);
  mesh_adapt(m, size_floor, good_qual_floor, nsliver_layers, max_ops);
  for (unsigned i = 0; i < 2; ++i) {
    for (unsigned j = 0; j < 4; ++j) {
      mesh_eval_field(m, 0, "warp", 3, warp_fun);
      printf("new warp field\n");
      warped_adapt(m);
      mesh_free_tag(m, 0, "warp");
    }
    the_rotation = -the_rotation;
  }
  free_mesh(m);
  comm_fini();
}
Пример #5
0
static void destroy(void *void_data) {
    struct cube_data *data = (struct cube_data*) void_data;

    free_mesh(data->mesh);
    free_shader(data->shader);
    list_free_keep_elements(data->uniforms);

    free(data);
}
PresetInputs::~PresetInputs()
{
	this->origx = free_mesh ( this->origx );
	this->origy = free_mesh ( this->origy );
	this->origrad = free_mesh ( this->origrad );
	this->origtheta = free_mesh ( this->origtheta );
	this->x_mesh = free_mesh ( this->x_mesh );
	this->y_mesh = free_mesh ( this->y_mesh );
	this->rad_mesh = free_mesh ( this->rad_mesh );
	this->theta_mesh = free_mesh ( this->theta_mesh );
}
Пример #7
0
/* used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c */
void free_libblock(ListBase *lb, void *idv)
{
	ID *id= idv;

#ifdef WITH_PYTHON
	BPY_id_release(id);
#endif

	switch( GS(id->name) ) {	/* GetShort from util.h */
		case ID_SCE:
			free_scene((Scene *)id);
			break;
		case ID_LI:
			free_library((Library *)id);
			break;
		case ID_OB:
			free_object((Object *)id);
			break;
		case ID_ME:
			free_mesh((Mesh *)id);
			break;
		case ID_CU:
			free_curve((Curve *)id);
			break;
		case ID_MB:
			free_mball((MetaBall *)id);
			break;
		case ID_MA:
			free_material((Material *)id);
			break;
		case ID_TE:
			free_texture((Tex *)id);
			break;
		case ID_IM:
			free_image((Image *)id);
			break;
		case ID_LT:
			free_lattice((Lattice *)id);
			break;
		case ID_LA:
			free_lamp((Lamp *)id);
			break;
		case ID_CA:
			free_camera((Camera*) id);
			break;
		case ID_IP:
			free_ipo((Ipo *)id);
			break;
		case ID_KE:
			free_key((Key *)id);
			break;
		case ID_WO:
			free_world((World *)id);
			break;
		case ID_SCR:
			free_screen((bScreen *)id);
			break;
		case ID_VF:
			free_vfont((VFont *)id);
			break;
		case ID_TXT:
			free_text((Text *)id);
			break;
		case ID_SCRIPT:
			//XXX free_script((Script *)id);
			break;
		case ID_SPK:
			free_speaker((Speaker *)id);
			break;
		case ID_SO:
			sound_free((bSound*)id);
			break;
		case ID_GR:
			free_group_objects((Group *)id);
			break;
		case ID_AR:
			free_armature((bArmature *)id);
			break;
		case ID_AC:
			free_action((bAction *)id);
			break;
		case ID_NT:
			ntreeFreeTree((bNodeTree *)id);
			break;
		case ID_BR:
			free_brush((Brush *)id);
			break;
		case ID_PA:
			psys_free_settings((ParticleSettings *)id);
			break;
		case ID_WM:
			if(free_windowmanager_cb)
				free_windowmanager_cb(NULL, (wmWindowManager *)id);
			break;
		case ID_GD:
			free_gpencil_data((bGPdata *)id);
			break;
	}

	if (id->properties) {
		IDP_FreeProperty(id->properties);
		MEM_freeN(id->properties);
	}

	BLI_remlink(lb, id);

	/* this ID may be a driver target! */
	BKE_animdata_main_cb(G.main, animdata_dtar_clear_cb, (void *)id);

	MEM_freeN(id);
}
Пример #8
0
Файл: mesh.cpp Проект: tommp/V8
bool Mesh::load_from_file(Resource_manager& manager, const std::string& name){
	if( VBO != 0 ){
		free_mesh();
	}

	std::vector<Vertex> vertices;
	std::vector<GLuint> indices;
	std::string material_name = "";

	if (name == Mesh_vars::BOX) {
		if (!load_base_box(vertices)) {
			std::cout << __FILE__ << ":" << __LINE__ << ": " << "ERROR: Failed to load base box mesh!" << std::endl;
			errorlogger("ERROR: Failed to load base box mesh!");
			return false;
		}
	}

	else if (name == Mesh_vars::LINE) {
		if (!load_base_line(vertices)) {
			std::cout << __FILE__ << ":" << __LINE__ << ": " << "ERROR: Failed to load base box mesh!" << std::endl;
			errorlogger("ERROR: Failed to load base box mesh!");
			return false;
		}
	}

	else if (!load_binary_mesh(name, vertices, indices, material_name)) {
		std::cout << __FILE__ << ":" << __LINE__ << ": " << "ERROR: Failed to load binary mesh with name: " << name << std::endl;
		errorlogger("ERROR: Failed to load binary mesh with name: ", name.c_str());
		return false;
	}

	if (!material_name.empty()) {
		material = manager.load_material(material_name);
	}
	
	if (material && (material->is_complete())) {
		/* yolo */
	}
	else{
		std::cout << __FILE__ << ":" << __LINE__ << ": " << "WARNING: Using base color due to incomplete material: " << material_name << std::endl;
		errorlogger("WARNING: Using base color due to incomplete material: ", material_name.c_str());
		switch (base_context->shader_type) {
			case GEOMETRY_ANIMATED:
				base_context->shader_type = GEOMETRY_ANIMATED_COLORED;
				break;
			case GEOMETRY_STATIC:
				base_context->shader_type = GEOMETRY_STATIC_COLORED;
				break;
			case GEOMETRY_LINES:
				break;
			default:
				std::cout << __FILE__ << ":" << __LINE__ << ": " << "ERROR: Invalid shader type in context of mesh: " << name << std::endl;
				errorlogger("ERROR: Invalid shader type in context of mesh: ", name.c_str());
				return false;
		}
	}

	if (indices.size() > 0) {
		base_context->num_vertices = indices.size();
	}
	else{
		base_context->num_vertices = vertices.size();
	}

	glGenVertexArrays(1, &(base_context->VAO));
	glGenBuffers(1, &VBO);
  
	glBindVertexArray(base_context->VAO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), 
				 &vertices[0], GL_DYNAMIC_DRAW);


	if (base_context->render_elements){
		glGenBuffers(1, &EBO);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), 
					 &indices[0], GL_DYNAMIC_DRAW);
	}

	/* Position attribute */
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)0);
	
	/* Normal attribute */
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, normal));

	/* TexCoord attribute */
	glEnableVertexAttribArray(2);
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, tex_coords));

	/* TODO:: Make conditional after vertex struct split */
	/* Bone ID attribute */
	glEnableVertexAttribArray(3);
    glVertexAttribIPointer(3, 4, GL_INT, sizeof(Vertex), (GLvoid*)offsetof(Vertex, bone_ids));

    /* Bone weight attribute */
    glEnableVertexAttribArray(4); 
    glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, bone_weights));

	/* Unbind */
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindVertexArray(0); 

	/* Check for errors */
	if(check_ogl_error()){
		std::cout << __FILE__ << ":" << __LINE__ << ": " << "ERROR: Failed to load mesh from file with name: " << name << std::endl;
		errorlogger("ERROR: Failed to load mesh from file with name: ", name.c_str());
		return false;
	}

	return true;
}
Пример #9
0
int main(int argc, char *argv[])
{
    struct sparse_matrix_t *sparseA = NULL;
    struct vector_t *b = NULL;
    struct vector_t *x;
    struct mesh_t *mesh;
    char *xml_output;

    long int *compress2fat = NULL;
    struct vector_t *solution;
    struct vector_t *std_error_sol;
    long int fat_sol_nb_col;

    lsqr_input *input;
    lsqr_output *output;
    lsqr_work *work;            /* zone temoraire de travail */
    lsqr_func *func;            /* func->mat_vec_prod -> APROD */

    /* cmd line arg */
    char *mesh_filename = NULL;
    char *importfilename = NULL;
    char *output_filename = NULL;
    char *sol_error_filename = NULL;
    char *log_filename = NULL;
    char *output_type = NULL;
    int max_iter;
    double damping, grad_damping;
    int use_ach = 0;            /* ACH : tele-seismic inversion tomography */
    int check_sparse = 0;       /* check sparse matrix disable by default  */

    /* velocity model */
    char *vmodel = NULL;
    struct velocity_model_t *vm = NULL;

    struct mesh_t **imported_mesh = NULL;
    char **xmlfilelist = NULL;
    int nb_xmlfile = 0;

    int i, j;

    int nb_irm = 0;
    struct irm_t **irm = NULL;
    int *nb_metacell = NULL;

    FILE *logfd;

    /*************************************************************/
    parse_command_line(argc, argv,
                       &mesh_filename,
                       &vmodel,
                       &importfilename,
                       &log_filename,
                       &output_filename, &output_type,
                       &max_iter,
                       &damping, &grad_damping, &use_ach, &check_sparse);

    if (use_ach) {
        fprintf(stderr, "Using ACH tomographic inversion\n");
    } else {
        fprintf(stderr, "Using STANDARD tomographic inversion\n");
    }

    /* load the velocity model */
    if (vmodel) {
        char *myfile;
        vm = load_velocity_model(vmodel);
        if (!vm) {
            fprintf(stderr, "Can not initialize velocity model '%s'\n",
                    vmodel);
            exit(1);
        }
        myfile = strdup(vmodel);
        fprintf(stderr, "Velocity model '%s' loaded\n", basename(myfile));
        free(myfile);
    } else {
        vm = NULL;
    }

    /* Open log file */
    if (!log_filename) {
        logfd = stdout;
    } else {
        if (!(logfd = fopen(log_filename, "w"))) {
            perror(log_filename);
            exit(1);
        }
    }

    /*check_write_access (output_filename); */

    /**************************************/
    /* test if we can open file to import */
    /**************************************/
    if (importfilename) {
        xmlfilelist = parse_separated_list(importfilename, ",");
        nb_xmlfile = 0;
        while (xmlfilelist[nb_xmlfile]) {
            if (access(xmlfilelist[nb_xmlfile], R_OK) == -1) {
                perror(xmlfilelist[nb_xmlfile]);
                exit(1);
            }
            nb_xmlfile++;
        }
    } else {
        fprintf(stderr, "No file to import ... exiting\n");
        exit(0);
    }

    /****************************/
    /* main mesh initialization */
    /****************************/
    mesh = mesh_init_from_file(mesh_filename);
    if (!mesh) {
        fprintf(stderr, "Error decoding %s.\n", mesh_filename);
        exit(1);
    }
    fprintf(stderr, "read %s ok\n", mesh_filename);

    /*****************************************/
    /* check and initialize slice xml files  */
    /*****************************************/
    if (nb_xmlfile) {
        int nb_sparse = 0;
        int nb_res = 0;
        int f;

        imported_mesh =
            (struct mesh_t **) malloc(sizeof(struct mesh_t *) *
                                      nb_xmlfile);
        assert(imported_mesh);

        for (i = 0; i < nb_xmlfile; i++) {
            imported_mesh[i] = mesh_init_from_file(xmlfilelist[i]);
            if (!imported_mesh[i]) {
                fprintf(stderr, "Error decoding %s.\n", mesh_filename);
                exit(1);
            }
            for (f = 0; f < NB_MESH_FILE_FORMAT; f++) {
                /* mandatory field : res, sparse, and irm if provided */
                if (f == RES || f == SPARSE || f == IRM) {
                    check_files_access(f, imported_mesh[i]->data[f],
                                       xmlfilelist[i]);
                }
            }
            if (imported_mesh[i]->data[SPARSE]) {
                nb_sparse += imported_mesh[i]->data[SPARSE]->ndatafile;
            }

            if (imported_mesh[i]->data[RES]) {
                nb_res += imported_mesh[i]->data[RES]->ndatafile;
            }

            if (imported_mesh[i]->data[IRM]) {
                nb_irm += imported_mesh[i]->data[IRM]->ndatafile;
            }

        }

        if (!nb_sparse || !nb_res) {
            fprintf(stderr, "Error no sparse or res file available !\n");
            exit(0);
        }
    }

    /*********************************************/
    /* read and import the sparse(s) matrix(ces) */
    /*********************************************/
    for (i = 0; i < nb_xmlfile; i++) {
        if (!imported_mesh[i]->data[SPARSE]) {
            continue;
        }

        for (j = 0; j < imported_mesh[i]->data[SPARSE]->ndatafile; j++) {
            sparseA = import_sparse_matrix(sparseA,
                                           imported_mesh[i]->data[SPARSE]->
                                           filename[j]);
        }
    }

    if (check_sparse) {
        if (check_sparse_matrix(sparseA)) {
            exit(1);
        }
    }

    /*sparse_compute_length(sparseA, "length1.txt"); */
    fat_sol_nb_col = sparseA->nb_col;
    show_sparse_stats(sparseA);

    /*********************************************/
    /* read and import the residual time vector  */
    /*********************************************/
    for (i = 0; i < nb_xmlfile; i++) {
        if (!imported_mesh[i]->data[RES]) {
            continue;
        }

        for (j = 0; j < imported_mesh[i]->data[RES]->ndatafile; j++) {
            b = import_vector(b, imported_mesh[i]->data[RES]->filename[j]);
        }
    }

    /*************************************************/
    /* check compatibility between matrix and vector */
    /*************************************************/
    if (sparseA->nb_line != b->length) {
        fprintf(stderr,
                "Error, check your matrix/vector sizes (%ld/%ld)\n",
                sparseA->nb_line, b->length);
        exit(1);
    }

    /********************/
    /* show memory used */
    /********************/
#ifdef __APPLE__
    {
        struct mstats memusage;

        memusage = mstats();
        fprintf(stderr, "Memory used: %.2f MBytes\n",
                (float) (memusage.bytes_used) / (1024. * 1024));
    }
#else
    {
        struct mallinfo m_info;

        m_info = mallinfo();
        fprintf(stderr, "Memory used: %.2f MBytes\n",
                (float) (m_info.uordblks +
                         m_info.usmblks) / (1024. * 1024.));
    }
#endif

    /**************************************/
    /* relative traveltime mode           */
    /**************************************/
    if (use_ach) {
        int nb_evt_imported = 0;

        for (i = 0; i < nb_xmlfile; i++) {
            if (!imported_mesh[i]->data[EVT]) {
                continue;
            }

            for (j = 0; j < imported_mesh[i]->data[EVT]->ndatafile; j++) {
                relative_tt(sparseA, b,
                            imported_mesh[i]->data[EVT]->filename[j]);
                nb_evt_imported++;
            }
        }

        if (!nb_evt_imported) {
            fprintf(stderr,
                    "Error in ACH mode, can not import any .evt file !\n");
            exit(1);
        }
    }

    /************************************************/
    /* read the irregular mesh definition if needed */
    /* one by layer                                 */
    /************************************************/
    if (nb_irm) {
        int cpt = 0;
        struct mesh_offset_t **offset;
        int l;

        irm = (struct irm_t **) malloc(nb_irm * sizeof(struct irm_t *));
        assert(irm);
        nb_metacell = (int *) calloc(nb_irm, sizeof(int));
        assert(nb_metacell);

        make_mesh(mesh);

        for (i = 0; i < nb_xmlfile; i++) {
            if (!imported_mesh[i]->data[IRM]) {
                continue;
            }

            /* offset between meshes */
            offset = compute_mesh_offset(mesh, imported_mesh[i]);
            for (l = 0; l < mesh->nlayers; l++) {
                if (!offset[l])
                    continue;
                fprintf(stderr,
                        "\t%s, [%s] offset[layer=%d] : lat=%d lon=%d z=%d\n",
                        xmlfilelist[i], MESH_FILE_FORMAT[IRM], l,
                        offset[l]->lat, offset[l]->lon, offset[l]->z);
            }

            for (j = 0; j < imported_mesh[i]->data[IRM]->ndatafile; j++) {
                /* FIXME: read only once the irm file */
                irm[cpt] =
                    read_irm(imported_mesh[i]->data[IRM]->filename[j],
                             &(nb_metacell[cpt]));
                import2mesh_irm_file(mesh,
                                     imported_mesh[i]->data[IRM]->
                                     filename[j], offset);
                cpt++;
            }

            for (l = 0; l < mesh->nlayers; l++) {
                if (offset[l])
                    free(offset[l]);
            }
            free(offset);
        }
        metacell_find_neighbourhood(mesh);
    }

    /*sparse_compute_length(sparseA, "length1.txt"); */
    fat_sol_nb_col = sparseA->nb_col;
    show_sparse_stats(sparseA);

    /***********************/
    /* remove empty column */
    /***********************/
    fprintf(stderr, "starting compression ...\n");
    sparse_compress_column(mesh, sparseA, &compress2fat);
    if (check_sparse) {
        if (check_sparse_matrix(sparseA)) {
            exit(1);
        }
    }
    show_sparse_stats(sparseA);

    /***************************************/
    /* add gradient damping regularisation */
    /***************************************/
    if (fabs(grad_damping) > 1.e-6) {
        int nb_faces = 6;       /* 1 cell may have 6 neighbours */
        long int nb_lines = 0;
        char *regul_name;

        fprintf(stdout, "using gradient damping : %f\n", grad_damping);

        /* tmp file name */
        regul_name = tempnam("/tmp", "regul");
        if (!regul_name) {
            perror("lsqrsolve: ");
            exit(1);
        }

        if (nb_irm) {
            create_regul_DtD_irm(sparseA, compress2fat,
                                 mesh, regul_name, nb_faces,
                                 grad_damping, &nb_lines);
        } else {
            create_regul_DtD(sparseA, compress2fat,
                             mesh, regul_name, nb_faces,
                             grad_damping, &nb_lines);
        }

        sparse_matrix_resize(sparseA,
                             sparseA->nb_line + sparseA->nb_col,
                             sparseA->nb_col);

        sparseA = import_sparse_matrix(sparseA, regul_name);
        if (check_sparse) {
            if (check_sparse_matrix(sparseA)) {
                exit(1);
            }
        }
        vector_resize(b, sparseA->nb_line);
        unlink(regul_name);

        show_sparse_stats(sparseA);
    }

    /*********************************/
    /* the real mesh is no more used */
    /* keep only the light mesh      */
    /*********************************/
    fprintf(stdout,
            "Time to free the real mesh and keep only the light structure\n");
    free_mesh(mesh);
    mesh = mesh_init_from_file(mesh_filename);
    if (!mesh) {
        fprintf(stderr, "Error decoding %s.\n", mesh_filename);
        exit(1);
    }
    fprintf(stderr, "read %s ok\n", mesh_filename);

    /********************************/
    /* init vector solution to zero */
    /********************************/
    x = new_vector(sparseA->nb_col);

    /*************************************************************/
    /* solve A.x = B                                             */
    /* A = ray length in the cells                               */
    /* B = residual travel time observed - computed              */
    /* x solution to satisfy the lsqr problem                    */
    /*************************************************************/

    /* LSQR alloc */
    alloc_lsqr_mem(&input, &output, &work, &func, sparseA->nb_line,
                   sparseA->nb_col);

    fprintf(stderr, "alloc_lsqr_mem : ok\n");

    /* defines the routine Mat.Vect to use */
    func->mat_vec_prod = sparseMATRIXxVECTOR;

    /* Set the input parameters for LSQR */
    input->num_rows = sparseA->nb_line;
    input->num_cols = sparseA->nb_col;
    input->rel_mat_err = 1.0e-3;        /* in km */
    input->rel_rhs_err = 1.0e-2;        /* in seconde */
    /*input->rel_mat_err = 0.;
       input->rel_rhs_err = 0.; */
    input->cond_lim = .0;
    input->lsqr_fp_out = logfd;
    /* input->rhs_vec = (dvec *) b; */
    dvec_copy((dvec *) b, input->rhs_vec);
    input->sol_vec = (dvec *) x;        /* initial guess */
    input->damp_val = damping;
    if (max_iter == -1) {
        input->max_iter = 4 * (sparseA->nb_col);
    } else {
        input->max_iter = max_iter;
    }

    /* catch Ctrl-C signal */
    signal(SIGINT, emergency_halt);

    /******************************/
    /* resolution du systeme Ax=b */

    /******************************/
    lsqr(input, output, work, func, sparseA);
    fprintf(stderr, "*** lsqr ended (%ld iter) : %s\n",
            output->num_iters, lsqr_msg[output->term_flag]);
    if (output->term_flag == 0) {       /* solution x=x0 */
        exit(0);
    }

    /* uncompress the solution  */
    solution = uncompress_column((struct vector_t *) output->sol_vec,
                                 compress2fat, fat_sol_nb_col);

    /* uncompress the standard error on solution  */
    std_error_sol =
        uncompress_column((struct vector_t *) output->std_err_vec,
                          compress2fat, fat_sol_nb_col);

    /* if irm file was provided, set the right value to each cell 
     * from a given metacell 
     */
    if (irm) {
        irm_update(solution, irm, nb_metacell, nb_irm, mesh);
        free_irm(irm, nb_irm);
        free(nb_metacell);
    }

    /* write solution */
    if (strchr(output_type, 'm')) {
        export2matlab(solution, output_filename, mesh, vm,
                      output->num_iters,
                      input->damp_val, grad_damping, use_ach);
    }

    if (strchr(output_type, 's')) {
        export2sco(solution, output_filename, mesh, vm,
                   output->num_iters,
                   input->damp_val, grad_damping, use_ach);
    }

    if (strchr(output_type, 'g')) {
        /* solution */
        export2gmt(solution, output_filename, mesh, vm,
                   output->num_iters,
                   input->damp_val, grad_damping, use_ach);

        /* error on solution */
        sol_error_filename = (char *)
            malloc(sizeof(char) *
                   (strlen(output_filename) + strlen(".err") + 1));
        sprintf(sol_error_filename, "%s.err", output_filename);
        export2gmt(std_error_sol, sol_error_filename, mesh, vm,
                   output->num_iters,
                   input->damp_val, grad_damping, use_ach);
        free(sol_error_filename);

    }

    /* save the xml enrichied with sections */
    xml_output = (char *)
        malloc((strlen(output_filename) + strlen(".xml") +
                1) * sizeof(char));
    assert(xml_output);
    sprintf(xml_output, "%s.xml", output_filename);
    mesh2xml(mesh, xml_output);
    free(xml_output);

    /******************************************************/
    /* variance reduction, ie how the model fits the data */
    /* X = the final solution                             */
    /*                                                    */
    /*                 ||b-AX||²                          */
    /*         VR= 1 - --------                           */
    /*                  ||b||²                            */
    /*                                                    */
    /******************************************************/
    {
        double norm_b;
        double norm_b_AX;
        double VR;              /* variance reduction */

        struct vector_t *rhs;   /* right hand side */
        rhs = new_vector(sparseA->nb_line);

        /* use copy */
        dvec_copy((dvec *) b, (dvec *) rhs);

        norm_b = dvec_norm2((dvec *) rhs);

        /* does rhs = rhs + sparseA . output->sol_vec */
        /* here  rhs is overwritten */
        dvec_scale((-1.0), (dvec *) rhs);
        sparseMATRIXxVECTOR(0, output->sol_vec, (dvec *) rhs, sparseA);
        dvec_scale((-1.0), (dvec *) rhs);

        norm_b_AX = dvec_norm2((dvec *) rhs);

        VR = 1 - (norm_b_AX * norm_b_AX) / (norm_b * norm_b);
        fprintf(stdout, "Variance reduction = %.2f%%\n", VR * 100);
        free_vector(rhs);
    }

    /********/
    /* free */
    /********/
    if (vm) {
        free_velocity_model(vm);
    }
    free_mesh(mesh);
    free_sparse_matrix(sparseA);
    free_lsqr_mem(input, output, work, func);

    free_vector(solution);
    free_vector(std_error_sol);
    free(compress2fat);

    for (i = 0; i < nb_xmlfile; i++) {
        free(xmlfilelist[i]);
        free_mesh(imported_mesh[i]);
    }
    free(xmlfilelist);
    free(imported_mesh);
    return (0);
}
Пример #10
0
void fem(size_t n, double errors[2], double (*fn_f)(double, double),
         double (*fn_g)(unsigned char, double, double),
         double (*fn_u)(double, double))
{
  mesh m;
  crs_matrix mat;
  double * u, * rhs;
  double local_stiffness[3][3];
  double local_load[3];
  size_t elem;

  /* 1. Allocate and generate mesh */
  get_mesh(&m, n);

#ifdef PRINT_DEBUG
  print_mesh(&m);
#endif

  /* 2. Allocate the linear system */
  init_matrix(&mat, &m);

  u = (double *) malloc(sizeof(double) * m.n_vertices);
  if (u == NULL) err_exit("Allocation of solution vector failed!");
  memset(u, 0, sizeof(double) * m.n_vertices);

  rhs = (double *) malloc(sizeof(double) * m.n_vertices);
  if (rhs == NULL)
    err_exit("Allocation of right hand side failed!");
  memset(rhs, 0, sizeof(double) * m.n_vertices);

  /* 3. Assemble the matrix */
  for (elem = 0; elem <  m.n_triangles; ++elem)
  {
    /* Compute local stiffness and load */
    get_local_stiffness(local_stiffness, &m, elem);
    get_local_load(local_load, &m, elem, fn_f);

#ifdef PRINT_DEBUG
    print_local_stiffness(local_stiffness);
    print_local_load(local_load);
#endif

    /* insert into global matrix and rhs */
    assemble_local2global_stiffness(local_stiffness, &mat, &m, elem);
    assemble_local2global_load(local_load, rhs, &m, elem);
  }

#ifdef PRINT_DEBUG
  printf("Matrix after assembly:\n");
  print_matrix(&mat);
  printf("rhs after assembly:\n");
  for(size_t i = 0; i < m.n_vertices; ++i) {
      printf("%5.2f\n", rhs[i]);
  }
  printf("\n");
#endif

  /* 4. Apply boundary conditions */
  apply_dbc(&mat, rhs, &m, fn_g);

#ifdef PRINT_DEBUG
  printf("Matrix after application of BCs:\n");
  print_matrix(&mat);
  printf("rhs after application of BCs:\n");
  for(size_t i = 0; i < m.n_vertices; ++i) {
      printf("%5.2f\n", rhs[i]);
  }
  printf("\n");
#endif

  /* 5. Solve the linear system */
  solve(&mat, u, rhs);

  /* 6. Evaluate error */
  errors[0] = l2_norm(u, &m, fn_u);
  errors[1] = inf_norm(u, &m, fn_u);

  /* free allocated resources */
  free(u);
  free(rhs);
  rhs = NULL;
  free_matrix(&mat);
  free_mesh(&m);
}
Пример #11
0
/**
 * Loads a model from a file.
 * Returns a pointer to the bone struct containing the data loaded.
 */
model *load_model(const char *file_name)
{
  FILE *fp;
  char buffer[BUFF_LEN], *arg_list[MAX_ARGS];
  int i, line = 0, arg_count;
  mesh *geo;
  bone *b_new;
  model *new_mdl = NULL;


  /* Attempt to open the requested file. Prints error message on error. */
  if((fp = fopen(file_name, "r")) == NULL)
  {
    fprintf(stderr, "ERROR(load_model): Unable to open file '%s'.\n",
      file_name);
    return NULL;
  }

  while(fgets(buffer, BUFF_LEN - 1, fp) != NULL)
  {
    line++;

    /* No lines should be more then the max buffer size in length. If any
     * lines do breach this contraint, then the file is corrupt and will
     * not be loaded. */
    if(buffer[strlen(buffer) - 1] != '\n')
    {
      fprintf(stderr,
        "ERROR(load_model): Buffer overflow in file '%s' line %d\n", file_name,
        line);
      return NULL;
    }
    buffer[strlen(buffer) - 1] = '\0';

    arg_count = makeargs(buffer, SEPERATOR, arg_list, MAX_ARGS);
    if(arg_count == 0)
      continue;


    /* If there's an m as the first character (which there should be at the
     * head of each model file) then we prepare the model.  */
    if(buffer[0] == 'm')
    {
      if(arg_count != 4)
        continue;

      /* Create a new model struct. */
      new_mdl = new_model(arg_list[1], atoi(arg_list[2]));
      if(new_mdl == NULL) return NULL;

      /* Initialise all the new models variables. */
      new_mdl->texture = loadTexture(arg_list[3]);

      printf("New model '%s' created. Loading Model...\n", arg_list[1]);
    }


    /* If we have a bone, indicated by a b as the first character. Note that
     * bones can only be added if a model line has been read in. */
    else if(buffer[0] == 'b')
    {
      if(new_mdl == NULL)
      {
        fprintf(stderr,
          "ERROR(load_mdl): Attempted load bone without model decl.\n");
        continue;
      }
      if(arg_count < 7) continue;

      printf("Loading bone '%s' into model '%s'.\n", arg_list[1],
          new_mdl->name);

      new_mdl->n_bones++;
      /* Allocate memory for the bone object and various chores that need
       * to be done to the bone to keep it healthy. */
      b_new = malloc(sizeof(bone));
      if(b_new == NULL)
      {
        fprintf(stderr, "ERROR(load_model): Cannot allocate memory.\n");
        exit(1);
      }
      b_new->child = NULL;
      b_new->sibling = NULL;
      b_new->child_count = 0;

      /**
       * Allocate memory for the bone name and copy the string accross.
       */
      b_new->name = malloc(strlen(arg_list[1]));
      strcpy(b_new->name, arg_list[1]);

      /* Parse translations from the strings and put them into the bone's
       * translation struct. */
      for(i = 0; i < TRANS_SIZE; i++)
        b_new->rot[i] = atof(arg_list[i + 2]);

      b_new->length = atof(arg_list[5]);

      /* Attempt to load a new mesh into the current bone.  */
      if(strlen(arg_list[7]) > 0)
      {
        geo = load_obj(arg_list[7]);
        if(geo == NULL)
        {
          fprintf(stderr, "Error loading obj %s\n", arg_list[7]);
          exit(1);
        }

        /* Create a vertex array out of the loaded obj and free the mesh
         * struct that was temporarily created. */
        if(strlen(arg_list[8]) > 0 && arg_list[8][0] == 'F')
          b_new->geometry = mesh_to_array(geo, NORM_FLAT);
        else
          b_new->geometry = mesh_to_array(geo, NORM_SMOOTH);
        b_new->tri_count = geo->n_elements;
        free_mesh(geo);
      }
      else
        b_new->geometry = NULL;

      /* If the root bone has not been set then this is obviously the root
       * bone, or a file format error. */
      if(new_mdl->root == NULL)
      {
        if(strlen(arg_list[6]) == 0)
          new_mdl->root = b_new;
        else
        {
          fprintf(stderr,
            "ERROR(load_model): Error, root bone must not have parent.\n");
          free_model(new_mdl);
          return NULL;
        }
      }
      else
      {
        if(!skel_add_child(arg_list[6], new_mdl->root, b_new))
        {
          printf("Cannot add child %s.\n", b_new->name);
          free_model(new_mdl);
          return NULL;
        }
      }
    }


    /* Start of an animation. */
    else if(buffer[0] == 'a')
    {
      if(new_mdl == NULL)
      {
        fprintf(stderr,
          "ERROR(load_mdl): Attempted load animation without model decl.\n");
        continue;
      }
      if(arg_count != 2) continue;

      load_animation(new_mdl, atoi(arg_list[1]), fp);
    }
  }

  if(new_mdl != NULL)
    new_mdl->bone_array = skel_make_array(new_mdl->root, new_mdl->n_bones);

  printf("New model '%s' successfully loaded.\n", new_mdl->name);
  printf("%d bones loaded.\n", new_mdl->n_bones);
  printf("%d animations loaded.\n", new_mdl->n_anims);

  return new_mdl;
}
Пример #12
0
PresetOutputs::~PresetOutputs()
{
	assert(this->gx > 0);

	this->rad_mesh = free_mesh(this->rad_mesh);
	this->sx_mesh  = free_mesh(this->sx_mesh);
	this->sy_mesh  = free_mesh(this->sy_mesh);
	this->dy_mesh  = free_mesh(this->dy_mesh);
	this->dx_mesh  = free_mesh(this->dx_mesh);
	this->cy_mesh  = free_mesh(this->cy_mesh);
	this->cx_mesh  = free_mesh(this->cx_mesh);
	this->warp_mesh = free_mesh(this->warp_mesh);
	this->zoom_mesh = free_mesh(this->zoom_mesh);
	this->zoomexp_mesh = free_mesh(this->zoomexp_mesh);
	this->rot_mesh = free_mesh(this->rot_mesh);
	this->orig_x   = free_mesh(this->orig_x);
	this->orig_y   = free_mesh(this->orig_y);

    customWaves.clear();
    customShapes.clear();
    drawables.clear();
}