Ejemplo n.º 1
0
int main(int argc, char **argv) {
	int res = ERR_SUCCESS;

#ifdef WITH_PETSC
	PetscInitialize(&argc, &argv, (char *) PETSC_NULL, PETSC_NULL);
#endif
	set_verbose(false);

	if (argc < 5) error("Not enough parameters.");

	H1ShapesetLobattoHex shapeset;

	printf("* Loading mesh '%s'\n", argv[1]);
	Mesh mesh;
	Mesh3DReader mloader;
	if (!mloader.load(argv[1], &mesh)) error("Loading mesh file '%s'\n", argv[1]);

	printf("* Setting the space up\n");
	H1Space space(&mesh, &shapeset);
	space.set_bc_types(bc_types);
	space.set_essential_bc_values(essential_bc_values);

	int o[3] = { 0, 0, 0 };
	sscanf(argv[2], "%d", o + 0);
	sscanf(argv[3], "%d", o + 1);
	sscanf(argv[4], "%d", o + 2);
	order3_t order(o[0], o[1], o[2]);
	printf("  - Setting uniform order to (%d, %d, %d)\n", order.x, order.y, order.z);
	space.set_uniform_order(order);

	WeakForm wf;
	wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<ord_t, ord_t>, SYM, ANY);
	wf.add_vector_form(linear_form<double, scalar>, linear_form<ord_t, ord_t>, ANY);

	LinearProblem lp(&wf);
	lp.set_space(&space);

	bool done = false;
	int iter = 0;
	do {
		Timer assemble_timer("Assembling stiffness matrix");
		Timer solve_timer("Solving stiffness matrix");

		printf("\n=== Iter #%d ================================================================\n", iter);

		printf("\nSolution\n");

#if defined WITH_UMFPACK
		UMFPackMatrix mat;
		UMFPackVector rhs;
		UMFPackLinearSolver solver(&mat, &rhs);
#elif defined WITH_PARDISO
		PardisoMatrix mat;
		PardisoVector rhs;
		PardisoLinearSolver solver(&mat, &rhs);
#elif defined WITH_PETSC
		PetscMatrix mat;
		PetscVector rhs;
		PetscLinearSolver solver(&mat, &rhs);
#elif defined WITH_MUMPS
		MumpsMatrix mat;
		MumpsVector rhs;
		MumpsSolver solver(&mat, &rhs);
#endif

		int ndofs = space.assign_dofs();
		printf("  - Number of DOFs: %d\n", ndofs);

		// assemble stiffness matrix
		printf("  - Assembling... "); fflush(stdout);
		assemble_timer.reset();
		assemble_timer.start();
		lp.assemble(&mat, &rhs);
		assemble_timer.stop();
		printf("done in %s (%lf secs)\n", assemble_timer.get_human_time(), assemble_timer.get_seconds());

		// solve the stiffness matrix
		printf("  - Solving... "); fflush(stdout);
		solve_timer.reset();
		solve_timer.start();
		bool solved = solver.solve();
		solve_timer.stop();
		if (solved)
			printf("done in %s (%lf secs)\n", solve_timer.get_human_time(), solve_timer.get_seconds());
		else {
			res = ERR_FAILURE;
			printf("failed\n");
			break;
		}

		printf("Reference solution\n");

#if defined WITH_UMFPACK
		UMFPackLinearSolver rsolver(&mat, &rhs);
#elif defined WITH_PARDISO
		PardisoLinearSolver rsolver(&mat, &rhs);
#elif defined WITH_PETSC
		PetscLinearSolver rsolver(&mat, &rhs);
#elif defined WITH_MUMPS
		MumpsSolver rsolver(&mat, &rhs);
#endif

		Mesh rmesh;
		rmesh.copy(mesh);
		rmesh.refine_all_elements(H3D_H3D_H3D_REFT_HEX_XYZ);

		Space *rspace = space.dup(&rmesh);
		rspace->copy_orders(space, 1);

		LinearProblem rlp(&wf);
		rlp.set_space(rspace);

		int rndofs = rspace->assign_dofs();
		printf("  - Number of DOFs: %d\n", rndofs);

		printf("  - Assembling... "); fflush(stdout);
		assemble_timer.reset();
		assemble_timer.start();
		rlp.assemble(&mat, &rhs);
		assemble_timer.stop();
		printf("done in %s (%lf secs)\n", assemble_timer.get_human_time(), assemble_timer.get_seconds());

		printf("  - Solving... "); fflush(stdout);
		solve_timer.reset();
		solve_timer.start();
		bool rsolved = rsolver.solve();
		solve_timer.stop();
		if (rsolved)
			printf("done in %s (%lf secs)\n", solve_timer.get_human_time(), solve_timer.get_seconds());
		else {
			res = ERR_FAILURE;
			printf("failed\n");
			break;
		}

		Solution sln(&mesh);
		sln.set_coeff_vector(&space, solver.get_solution());

		Solution rsln(&rmesh);
		rsln.set_coeff_vector(rspace, rsolver.get_solution());

		printf("Adaptivity:\n");
		H1Adapt hp(&space);
		double tol = hp.calc_error(&sln, &rsln) * 100;
		printf("  - tolerance: "); fflush(stdout);
		printf("% lf\n", tol);
		if (tol < TOLERANCE) {
			printf("\nDone\n");
			ExactSolution ex_sln(&mesh, exact_solution);
			// norm
			double h1_sln_norm = h1_norm(&sln);
			double h1_err_norm = h1_error(&sln, &ex_sln);
			printf("  - H1 solution norm:   % le\n", h1_sln_norm);
			printf("  - H1 error norm:      % le\n", h1_err_norm);

			double l2_sln_norm = l2_norm(&sln);
			double l2_err_norm = l2_error(&sln, &ex_sln);
			printf("  - L2 solution norm:   % le\n", l2_sln_norm);
			printf("  - L2 error norm:      % le\n", l2_err_norm);

			if (h1_err_norm > EPS || l2_err_norm > EPS) {
				// calculated solution is not enough precise
				res = ERR_FAILURE;
			}

			break;
		}

		Timer t("");
		printf("  - adapting... "); fflush(stdout);
		t.start();
		hp.adapt(THRESHOLD);
		t.stop();
		printf("done in %lf secs (refined %d element(s))\n", t.get_seconds(), hp.get_num_refined_elements());

		iter++;
	} while (!done);


#ifdef WITH_PETSC
	PetscFinalize();
#endif

	return res;
}
Ejemplo n.º 2
0
int main(int argc, const char *argv[]) {

	const char *socket = NULL;

	mem_init();
	atexit(mem_exit);

	terminal_init();

	// --------------------------------------------
	// parse the parameters

        // Check -v (verbose) first to enable log_debug()
        // when processing other options
        for (int i=1; i < argc; i++) if (!strcmp("-v", argv[i])) set_verbose(1);

	int p = 1;
	while (p < argc && argv[p][0]=='-') {

		switch(argv[p][1]) {
		case 0:
			// single '-' option ends parameter processing
			p++;
			goto endpars;
		case 'v':
                	assert_single_char(argv[p]);
			// verbose is already checked above
			set_verbose(1);
			break;
            	case '?':
                	assert_single_char(argv[p]);
                	usage(EXIT_SUCCESS);    /* usage() exits already */
                	break;
		case 'T':
			assert_single_char(argv[p]);
                	if (p < argc-2) {
                  		p++;
                  		socket = argv[p];
                  		log_info("main: tools socket = %s\n", socket);
                	} else {
                  		log_error("-T requires <socket name> parameter\n");
                  		exit(EXIT_RESPAWN_NEVER);
                	}
                	break;
            	default:
                	log_error("Unknown command line option %s\n", argv[p]);
                	usage(EXIT_RESPAWN_NEVER);
                	break;
		}
		p++;
	}
endpars:
	// --------------------------------------------
	// open the socket

        if (socket == NULL) {
                const char *home = os_get_home_dir();
                socket = malloc_path(home, ".xdtools");
        }

	int sockfd = socket_open(socket, 0);
	if (sockfd < 0) {
		log_errno("Could not open socket %s\n", socket);
		mem_free(socket);
		exit(1);
	}
	mem_free(socket);

	// --------------------------------------------
	// find our command either as ending part of the name of the binary ...
	

	const cmdtab_t *cmd = NULL;
	int l = strlen(argv[0]);

	for (int i = 0; i < numcmds; i++) {
		int cl = strlen(cmdtab[i].name);

		if ((cl <= l)
			&& !strcmp(cmdtab[i].name, &argv[0][l-cl])) {
			cmd = &cmdtab[i];
			break;
		}
	}
	// ... or as command line parameter
	if (p < argc) {
		l = strlen(argv[p]);
		if (cmd == NULL) {
			for (int i = 0; i < numcmds; i++) {
				int cl = strlen(cmdtab[i].name);

				if ((cl <= l)
					&& !strcmp(cmdtab[i].name, argv[p])) {
					cmd = &cmdtab[i];
					p++;
					break;
				}
			}
		}
	}

	if (cmd == NULL) {
		log_error("Could not identify any of the commands!\n");
		usage(1);
	}	

	int rv = cmd->func(sockfd, argc-p, argv+p);


	close(sockfd);

	return rv;
}
Ejemplo n.º 3
0
int
udpxy_main( int argc, char* const argv[] )
{
    int rc = 0, ch = 0, port = -1,
        custom_log = 0, no_daemon = 0;

    char ipaddr[IPADDR_STR_SIZE] = "\0",
         mcast_addr[IPADDR_STR_SIZE] = "\0";

    char pidfile[ MAXPATHLEN ] = "\0";
    u_short MIN_MCAST_REFRESH = 0, MAX_MCAST_REFRESH = 0;

/* support for -r -w (file read/write) option is disabled by default;
 * those features are experimental and for dev debugging ONLY
 * */
#ifdef UDPXY_FILEIO
    static const char UDPXY_OPTMASK[] = "TvSa:l:p:m:c:B:n:R:r:w:H:M:";
#else
    static const char UDPXY_OPTMASK[] = "TvSa:l:p:m:c:B:n:R:H:M:";
#endif

    struct sigaction qact, iact, cact, oldact;

    mk_app_info(g_udpxy_app, g_app_info, sizeof(g_app_info) - 1);
    (void) get_pidstr( PID_RESET, "S" );

    rc = init_uopt( &g_uopt );
    while( (0 == rc) && (-1 != (ch = getopt(argc, argv, UDPXY_OPTMASK))) ) {
        switch( ch ) {
            case 'v': set_verbose( &g_uopt.is_verbose );
                      break;
            case 'T': no_daemon = 1;
                      break;
            case 'S': g_uopt.cl_tpstat = uf_TRUE;
                      break;
            case 'a':
                      rc = get_ipv4_address( optarg, ipaddr, sizeof(ipaddr) );
                      if( 0 != rc ) {
                        (void) fprintf( stderr, "Invalid address: [%s]\n",
                                        optarg );
                          rc = ERR_PARAM;
                      }
                      break;

            case 'p':
                      port = atoi( optarg );
                      if( port <= 0 ) {
                        (void) fprintf( stderr, "Invalid port number: [%d]\n",
                                        port );
                        rc = ERR_PARAM;
                      }
                      break;

            case 'm':
                      rc = get_ipv4_address( optarg, mcast_addr,
                              sizeof(mcast_addr) );
                      if( 0 != rc ) {
                        (void) fprintf( stderr, "Invalid multicast address: "
                                "[%s]\n", optarg );
                          rc = ERR_PARAM;
                      }
                      break;

            case 'c':
                      g_uopt.max_clients = atoi( optarg );
                      if( (g_uopt.max_clients < MIN_CLIENT_COUNT) ||
                          (g_uopt.max_clients > MAX_CLIENT_COUNT) ) {
                        (void) fprintf( stderr,
                                "Client count should be between %d and %d\n",
                                MIN_CLIENT_COUNT, MAX_CLIENT_COUNT );
                        rc = ERR_PARAM;
                      }
                      break;

            case 'l':
                      g_flog = fopen( optarg, "a" );
                      if( NULL == g_flog ) {
                        rc = errno;
                        (void) fprintf( stderr, "Error opening logfile "
                                "[%s]: %s\n",
                                optarg, strerror(rc) );
                        rc = ERR_PARAM;
                        break;
                      }

                      Setlinebuf( g_flog );
                      custom_log = 1;
                      break;

            case 'B':
                      rc = a2size(optarg, &g_uopt.rbuf_len);
                      if( 0 != rc ) {
                            (void) fprintf( stderr, "Invalid buffer size: [%s]\n",
                                    optarg );
                            exit( ERR_PARAM );
                      }
                      else if( (g_uopt.rbuf_len < MIN_MCACHE_LEN) ||
                          (g_uopt.rbuf_len > MAX_MCACHE_LEN) ) {
                        fprintf(stderr, "Buffer size "
                                "must be within [%ld-%ld] bytes\n",
                                (long)MIN_MCACHE_LEN, (long)MAX_MCACHE_LEN );
                        rc = ERR_PARAM;
                      }
                      break;

            case 'n':
                      g_uopt.nice_incr = atoi( optarg );
                      if( 0 == g_uopt.nice_incr ) {
                        (void) fprintf( stderr,
                            "Invalid nice-value increment: [%s]\n", optarg );
                        rc = ERR_PARAM;
                        break;
                      }
                      break;

            case 'R':
                      g_uopt.rbuf_msgs = atoi( optarg );
                      if( (g_uopt.rbuf_msgs <= 0) && (-1 != g_uopt.rbuf_msgs) ) {
                        (void) fprintf( stderr,
                                "Invalid Rmsgs size: [%s]\n", optarg );
                        rc = ERR_PARAM;
                        break;
                      }
                      break;

            case 'H':
                      g_uopt.dhold_tmout = (time_t)atoi( optarg );
                      if( (0 == g_uopt.dhold_tmout) ||
                          ((g_uopt.dhold_tmout) < 0 && (-1 != g_uopt.dhold_tmout)) ) {
                        (void) fprintf( stderr, "Invalid value for max time "
                                "to hold buffered data: [%s]\n", optarg );
                        rc = ERR_PARAM;
                        break;
                      }
                      break;

    #ifdef UDPXY_FILEIO
            case 'r':
                      if( 0 != access(optarg, R_OK) ) {
                        perror("source file - access");
                        rc = ERR_PARAM;
                        break;
                      }

                      g_uopt.srcfile = strdup( optarg );
                      break;

            case 'w':
                      g_uopt.dstfile = strdup( optarg );
                      break;
    #endif /* UDPXY_FILEIO */
            case 'M':
                      g_uopt.mcast_refresh = (u_short)atoi( optarg );

                      MIN_MCAST_REFRESH = 30;
                      MAX_MCAST_REFRESH = 64000;
                      if( g_uopt.mcast_refresh &&
                         (g_uopt.mcast_refresh < MIN_MCAST_REFRESH ||
                          g_uopt.mcast_refresh > MAX_MCAST_REFRESH )) {
                            (void) fprintf( stderr, 
                                "Invalid multicast refresh period [%d] seconds, "
                                "min=[%d] sec, max=[%d] sec\n",
                                (int)g_uopt.mcast_refresh,
                                (int)MIN_MCAST_REFRESH, (int)MAX_MCAST_REFRESH );
                            rc = ERR_PARAM;
                            break;
                       }
                      break;

            case ':':
                      (void) fprintf( stderr,
                              "Option [-%c] requires an argument\n",
                                    optopt );
                      rc = ERR_PARAM;
                      break;
            case '?':
                      (void) fprintf( stderr,
                              "Unrecognized option: [-%c]\n", optopt );
                      rc = ERR_PARAM;
                      break;

            default:
                     usage( argv[0], stderr );
                     rc = ERR_PARAM;
                     break;
        }
    } /* while getopt */

    if (rc) {
        free_uopt( &g_uopt );
        return rc;
    }

    openlog( g_udpxy_app, LOG_CONS | LOG_PID, LOG_LOCAL0 );

    do {
        if( (argc < 2) || (port <= 0) || (rc != 0) ) {
            usage( argv[0], stderr );
            rc = ERR_PARAM; break;
        }

        if( '\0' == mcast_addr[0] ) {
            (void) strncpy( mcast_addr, IPv4_ALL, sizeof(mcast_addr) - 1 );
        }

        if( !custom_log ) {
            /* in debug mode output goes to stderr, otherwise to /dev/null */
            g_flog = ((uf_TRUE == g_uopt.is_verbose)
                    ? stderr
                    : fopen( "/dev/null", "a" ));
            if( NULL == g_flog ) {
                perror("fopen");
                rc = ERR_INTERNAL; break;
            }
        }

        if( 0 == geteuid() ) {
            if( !no_daemon ) {
                if( stderr == g_flog ) {
                    (void) fprintf( stderr,
                        "Logfile must be specified to run "
                        "in verbose mode in background\n" );
                    rc = ERR_PARAM; break;
                }

                if( 0 != (rc = daemonize(0, g_flog)) ) {
                    rc = ERR_INTERNAL; break;
                }
            }

            rc = set_pidfile( g_udpxy_app, port, pidfile, sizeof(pidfile) );
            if( 0 != rc ) {
                mperror( g_flog, errno, "set_pidfile" );
                rc = ERR_INTERNAL; break;
            }

            if( 0 != (rc = make_pidfile( pidfile, getpid(), g_flog )) )
                break;
        }

        qact.sa_handler = handle_quitsigs;
        sigemptyset(&qact.sa_mask);
        qact.sa_flags = 0;

        if( (sigaction(SIGTERM, &qact, &oldact) < 0) ||
            (sigaction(SIGQUIT, &qact, &oldact) < 0) ||
            (sigaction(SIGINT,  &qact, &oldact) < 0)) {
            perror("sigaction-quit");
            rc = ERR_INTERNAL; break;
        }

        iact.sa_handler = SIG_IGN;
        sigemptyset(&iact.sa_mask);
        iact.sa_flags = 0;

        if( (sigaction(SIGPIPE, &iact, &oldact) < 0) ) {
            perror("sigaction-ignore");
            rc = ERR_INTERNAL; break;
        }

        cact.sa_handler = handle_sigchld;
        sigemptyset(&cact.sa_mask);
        cact.sa_flags = 0;

        if( sigaction(SIGCHLD, &cact, &oldact) < 0 ) {
            perror("sigaction-sigchld");
            rc = ERR_INTERNAL; break;
        }

        syslog( LOG_NOTICE, "%s is starting\n", g_app_info );
        TRACE( printcmdln( g_flog, g_app_info, argc, argv ) );

        rc = srv_loop( ipaddr, port, mcast_addr );

        syslog( LOG_NOTICE, "%s is exiting with rc=[%d]\n",
                g_app_info, rc);
        TRACE( tmfprintf( g_flog, "%s is exiting with rc=[%d]\n",
                    g_udpxy_app, rc ) );
        TRACE( printcmdln( g_flog, g_app_info, argc, argv ) );
    } while(0);

    if( '\0' != pidfile[0] ) {
        if( -1 == unlink(pidfile) ) {
            mperror( g_flog, errno, "unlink [%s]", pidfile );
        }
    }

    if( g_flog && (stderr != g_flog) ) {
        (void) fclose(g_flog);
    }

    closelog();
    free_uopt( &g_uopt );

    return rc;
}
Ejemplo n.º 4
0
int main(int argc, char **argv) {
	int res = ERR_SUCCESS;

#ifdef WITH_PETSC
	PetscInitialize(&argc, &argv, (char *) PETSC_NULL, PETSC_NULL);
#endif
	set_verbose(false);

	if (argc < 3) error("Not enough parameters");

	printf("* Loading mesh '%s'\n", argv[1]);
	Mesh mesh;
	H3DReader mesh_loader;
	if (!mesh_loader.load(argv[1], &mesh)) error("Loading mesh file '%s'\n", argv[1]);

	int o;
	sscanf(argv[2], "%d", &o);
	printf("  - Setting uniform order to %d\n", o);

	printf("* Setting the space up\n");
	H1Space space(&mesh, bc_types, essential_bc_values, o);

	int ndofs = space.assign_dofs();
	printf("  - Number of DOFs: %d\n", ndofs);

	printf("* Calculating a solution\n");

#if defined WITH_UMFPACK
	UMFPackMatrix mat;
	UMFPackVector rhs;
	UMFPackLinearSolver solver(&mat, &rhs);
#elif defined WITH_PARDISO
	PardisoMatrix mat;
	PardisoVector rhs;
	PardisoLinearSolver solver(&mat, &rhs);
#elif defined WITH_PETSC
	PetscMatrix mat;
	PetscVector rhs;
	PetscLinearSolver solver(&mat, &rhs);
#elif defined WITH_MUMPS
	MumpsMatrix mat;
	MumpsVector rhs;
	MumpsSolver solver(&mat, &rhs);
#endif

	WeakForm wf;
	wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<Ord, Ord>, SYM);
	wf.add_vector_form(linear_form<double, scalar>, linear_form<Ord, Ord>);

	DiscreteProblem dp(&wf, &space, true);

	// assemble stiffness matrix
	Timer assemble_timer("Assembling stiffness matrix");
	assemble_timer.start();
	dp.assemble(&mat, &rhs);
	assemble_timer.stop();

	// solve the stiffness matrix
	Timer solve_timer("Solving stiffness matrix");
	solve_timer.start();
	bool solved = solver.solve();
	solve_timer.stop();

	// output the measured values
	printf("%s: %s (%lf secs)\n", assemble_timer.get_name(), assemble_timer.get_human_time(), assemble_timer.get_seconds());
	printf("%s: %s (%lf secs)\n", solve_timer.get_name(), solve_timer.get_human_time(), solve_timer.get_seconds());

	if (solved) {
		Solution sln(&mesh);
		sln.set_coeff_vector(&space, solver.get_solution());

		ExactSolution ex_sln(&mesh, exact_solution);
		// norm
		double h1_sln_norm = h1_norm(&sln);
		double h1_err_norm = h1_error(&sln, &ex_sln);

		printf(" - H1 solution norm:   % le\n", h1_sln_norm);
		printf(" - H1 error norm:      % le\n", h1_err_norm);

		double l2_sln_norm = l2_norm(&sln);
		double l2_err_norm = l2_error(&sln, &ex_sln);
		printf(" - L2 solution norm:   % le\n", l2_sln_norm);
		printf(" - L2 error norm:      % le\n", l2_err_norm);

		if (h1_err_norm > EPS || l2_err_norm > EPS) {
			// calculated solution is not enough precise
			res = ERR_FAILURE;
		}

#if 0 //def OUTPUT_DIR
		// output
		const char *of_name = OUTPUT_DIR "/solution.pos";
		FILE *ofile = fopen(of_name, "w");
		if (ofile != NULL) {
			ExactSolution ex_sln(&mesh, exact_solution);
			DiffFilter eh(&sln, &ex_sln);
//			DiffFilter eh_dx(&mesh, &sln, &ex_sln, FN_DX, FN_DX);
//			DiffFilter eh_dy(&mesh, &sln, &ex_sln, FN_DY, FN_DY);
//			DiffFilter eh_dz(&mesh, &sln, &ex_sln, FN_DZ, FN_DZ);

			GmshOutputEngine output(ofile);
			output.out(&sln, "Uh");
//			output.out(&sln, "Uh dx", FN_DX_0);
//			output.out(&sln, "Uh dy", FN_DY_0);
//			output.out(&sln, "Uh dz", FN_DZ_0);
			output.out(&eh, "Eh");
//			output.out(&eh_dx, "Eh dx");
//			output.out(&eh_dy, "Eh dy");
//			output.out(&eh_dz, "Eh dz");
			output.out(&ex_sln, "U");
//			output.out(&ex_sln, "U dx", FN_DX_0);
//			output.out(&ex_sln, "U dy", FN_DY_0);
//			output.out(&ex_sln, "U dz", FN_DZ_0);

			fclose(ofile);
		}
		else {
			warning("Can not open '%s' for writing.", of_name);
		}
#endif
	}

#ifdef WITH_PETSC
	mat.free();
	rhs.free();
	PetscFinalize();
#endif

	TRACE_END;

	return res;
}
Ejemplo n.º 5
0
int main(int argc, char *argv[]) {
	struct configuration conf= { NULL, NULL, NULL, 0 };

	GError *error= NULL;
	GOptionContext *context;

	g_thread_init(NULL);

	init_mutex= g_mutex_new();

	if(db == NULL && source_db != NULL){
		db = g_strdup(source_db);
	}

	context= g_option_context_new("multi-threaded MySQL loader");
	GOptionGroup *main_group= g_option_group_new("main", "Main Options", "Main Options", NULL, NULL);
	g_option_group_add_entries(main_group, entries);
	g_option_group_add_entries(main_group, common_entries);
	g_option_context_set_main_group(context, main_group);
	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print("option parsing failed: %s, try --help\n", error->message);
		exit(EXIT_FAILURE);
	}
	g_option_context_free(context);

	//prompt for password if it's NULL
	if ( sizeof(password) == 0 || ( password == NULL && askPassword ) ){
		password = passwordPrompt();
	}

	if (program_version) {
		g_print("myloader %s, built against MySQL %s\n", VERSION, MYSQL_VERSION_STR);
		exit(EXIT_SUCCESS);
	}

	set_verbose(verbose);

	if (!directory) {
		g_critical("a directory needs to be specified, see --help\n");
		exit(EXIT_FAILURE);
	} else {
		char *p= g_strdup_printf("%s/metadata", directory);
		if (!g_file_test(p, G_FILE_TEST_EXISTS)) {
			g_critical("the specified directory is not a mydumper backup\n");
			exit(EXIT_FAILURE);
		}
	}
	MYSQL *conn;
	conn= mysql_init(NULL);

	configure_connection(conn,"myloader");
	if (!mysql_real_connect(conn, hostname, username, password, NULL, port, socket_path, 0)) {
		g_critical("Error connection to database: %s", mysql_error(conn));
		exit(EXIT_FAILURE);
	}

	if (mysql_query(conn, "SET SESSION wait_timeout = 2147483")){
		g_warning("Failed to increase wait_timeout: %s", mysql_error(conn));
	}

	if (!enable_binlog)
		mysql_query(conn, "SET SQL_LOG_BIN=0");

	mysql_query(conn, "/*!40014 SET FOREIGN_KEY_CHECKS=0*/");
	conf.queue= g_async_queue_new();
	conf.ready= g_async_queue_new();

	guint n;
	GThread **threads= g_new(GThread*, num_threads);
	struct thread_data *td= g_new(struct thread_data, num_threads);
	for (n= 0; n < num_threads; n++) {
		td[n].conf= &conf;
		td[n].thread_id= n+1;
		threads[n]= g_thread_create((GThreadFunc)process_queue, &td[n], TRUE, NULL);
		g_async_queue_pop(conf.ready);
	}
	g_async_queue_unref(conf.ready);

	g_message("%d threads created", num_threads);

	restore_databases(&conf, conn);

	for (n= 0; n < num_threads; n++) {
		struct job *j= g_new0(struct job, 1);
		j->type = JOB_SHUTDOWN;
		g_async_queue_push(conf.queue, j);
	}

	for (n= 0; n < num_threads; n++) {
		g_thread_join(threads[n]);
	}

	restore_schema_post(conn);

	restore_schema_view(conn);

	restore_schema_triggers(conn);

	g_async_queue_unref(conf.queue);
	mysql_close(conn);
	mysql_thread_end();
	mysql_library_end();
	g_free(directory);
	g_free(td);
	g_free(threads);

	return errors ? EXIT_FAILURE : EXIT_SUCCESS;
}
Ejemplo n.º 6
0
int main(int argc, char ** argv)
{
#ifdef DEBUG
    QsLogging::Logger & logger = QsLogging::Logger::instance();
    logger.setLoggingLevel(QsLogging::TraceLevel);
    QDir dir;
    dir.setPath(qApp->applicationDirPath());
    dir.remove(QString("cpp_utils") + QString(".log"));
    const QString sLogPath(QDir(qApp->applicationDirPath()).filePath(QString("cpp_generator") + QString(".log")));
    QsLogging::DestinationPtr fileDestination(QsLogging::DestinationFactory::MakeFileDestination(sLogPath));
    QsLogging::DestinationPtr debugDestination(QsLogging::DestinationFactory::MakeDebugOutputDestination());
    logger.addDestination(debugDestination.get());
    logger.addDestination(fileDestination.get());

    QSettings settings(QSettings::IniFormat, QSettings::UserScope, "DoUML", "settings");
    settings.setIniCodec(QTextCodec::codecForName("UTF-8"));
    QString locale = settings.value("Main/encoding").toString();
    QTextCodec* codec = QTextCodec::codecForName(locale.toLatin1().constData());
    QTextCodec::setCodecForLocale(codec);

    QLOG_INFO() << " STARTING CPP_GENERATOR";

#endif
    //QTest::qSleep(7000);
    int port_index;
#ifndef _RUN_PLUGOUT_EXTERNAL_
    if (argc == 2) {
        port_index = 1;
        QLOG_INFO() << "Got two arguments from Douml as argv";
        QLOG_INFO() << "Using first port index mode";
    }
    else if (argc == 3) {
        QLOG_INFO() << "Got three arguments from Douml as argv";
        if (argv[1][1] == 'v') {
            QLOG_INFO() << "Using verbose mode";
            set_verbose();
        }
        else {
            QLOG_INFO() << "Using preserve mode";
            set_preserve();
        }
        QLOG_INFO() << "Using second port index mode";
        port_index = 2;
    }
    else if (argc == 4) {
        QLOG_INFO() << "Got four arguments from Douml as argv";
        QLOG_INFO() << "Using preserve mode";
        QLOG_INFO() << "Using verbose mode";
        QLOG_INFO() << "Using third port index mode";
        set_verbose();
        set_preserve();
        port_index = 3;
    }
    else {
        QLOG_INFO() << "Got too little or too much arguments from Douml, exiting";
        return 0;
    }
    if (UmlCom::connect(QString(argv[port_index]).toUInt())) {
#else
    port_index = 1;
    if (UmlCom::connect(5000)) {
#endif
        try {

            UmlCom::trace("<b>C++ generator</b> release 2.18<br>");
            UmlCom::traceAutoRaise(FALSE);
            UmlCom::targetItem()->generate();

            QString s;

            s = "<hr><font face=helvetica>Generation done : %1 warnings, %2 errors</font><br>";
            s=s.arg(QString::number(n_warnings())).arg(QString::number(n_errors()));

            UmlCom::trace(s.toLatin1().constData());

            UmlCom::showTrace();
            UmlCom::message("");

            UmlCom::bye(n_errors());
        }
        catch (...) {
            QLOG_INFO() << "unhandled exception caught";
        }
    }

    UmlCom::close();
    return 0;
}
Ejemplo n.º 7
0
double solve_constraints(int this_task)
{
	lprec *lp;
	int numVar = 0, *var = NULL, ret = 0, i, j, k, var_count;
	double *coeff = NULL, lhs,rhs, obj;
	char col_name[10];

	/* Creating a model */
	for(i = 1;i < this_task; i++)
		numVar+=i;	
	lp = make_lp(0, numVar);
	if(lp == NULL)
		ret = 1; /* Couldn't construct a new model */
		
	if(ret == 0) {
		var_count = 1;
		for(i = 1 ; i < this_task; i++){
			for(j = i+1 ; j <= this_task; j++)
			{
				sprintf(col_name, "%dNNP%d_%d", this_task, i, j);
				set_col_name(lp, var_count, col_name);
				var_count++;			
			}
		}
		/* create space large enough for one row(i.e. equation) */
		var = (int *) malloc(numVar * sizeof(*var));
		coeff = (double *) malloc(numVar * sizeof(*coeff));
		if((var == NULL) || (coeff == NULL))
			ret = 2;
	}	
	
	/* add the equations to lpsolve */
	if(ret == 0) {
		set_add_rowmode(lp, TRUE);
		/* --------------------adding EQN-D-------------------- */
		for(j = 2;j <= this_task;j++){
			var_count = 0;
			for(i = 1; i < j; i++){
				sprintf(col_name,"%dNNP%d_%d",this_task, i, j);
				var[var_count] = get_nameindex(lp, col_name, FALSE);
				coeff[var_count] = 1;
				var_count++;
			}

			lhs= 0;
			for(i = 1; i < j; i++)
				lhs+= nnp_min[i][j];
			lhs*= floor(R[this_task]/task[j].p);			
			
			rhs = 0;
			for(i = 1; i < j; i++)
				rhs += nnp_max[i][j];
			rhs *= ceil(R[this_task]/task[j].p);
			
			if(!add_constraintex(lp, var_count, coeff, var, GE, lhs))
				ret = 3;
			if(!add_constraintex(lp, var_count, coeff, var, LE, rhs))
				ret = 3;			
		}
	}
	
	if(ret == 0) {	
		/* --------------------adding EQN-E-------------------- */
		for(k = 2;k <= this_task;k++)
		{			
			var_count = 0;
			for(j = 2; j <= k; j++){
				for(i = 1; i < j; i++){
					sprintf(col_name,"%dNNP%d_%d",this_task, i, j);
					var[var_count] = get_nameindex(lp, col_name, FALSE);
					coeff[var_count] = 1;
					var_count++;
				}
			}
			
			rhs = 0;
			for(i = 1; i < k; i++)
				rhs += ceil(R[this_task]/task[i].p);
			if(!add_constraintex(lp, var_count, coeff, var, LE,rhs))
				ret = 3;
		}
	}
	
	if(ret == 0) {
		/* ------------------adding EQN-G & H------------------ */
		for(j = 2; j <= this_task ; j++){
			for(i = 1; i < j; i++){
				lhs= floor(R[this_task]/task[j].p) * nnp_min[i][j];
				sprintf(col_name,"%dNNP%d_%d",this_task, i, j);
				var[0] = get_nameindex(lp, col_name, FALSE);
				coeff[0] = 1;
				if(!add_constraintex(lp, 1, coeff, var, GE, lhs))
					ret = 3;
				
				rhs = min(ceil(R[this_task]/task[i].p), ceil(R[this_task]/task[j].p) * ceil(R[j]/task[i].p), ceil(R[this_task]/task[j].p) * nnp_max[i][j]);
				if(!add_constraintex(lp, 1, coeff, var, LE,rhs))
					ret = 3;
			}
		}
	}
	
	if(ret == 0) {
 		/* --------------------adding EQN-I-------------------- */
		for(i = 1; i < this_task; i++){
			var_count = 0;
			for(j = i+1; j <= this_task; j++){
				sprintf(col_name,"%dNNP%d_%d",this_task, i, j);
				var[var_count] = get_nameindex(lp, col_name, FALSE);
				coeff[var_count] = 1;
				var_count++;				
			}
			rhs = ceil(R[this_task]/task[i].p);
			if(!add_constraintex(lp, var_count, coeff, var, LE,rhs))
				ret = 3;
		}
	}
		
	set_add_rowmode(lp, FALSE);
	if(ret == 0) {
		/* -----------------set the objective----------------- */
		var_count = 0;
		for(i = 1 ; i < this_task; i++){
			for(j = i+1 ; j<= this_task; j++){
				sprintf(col_name,"%dNNP%d_%d",this_task, i, j);
				var[var_count] = get_nameindex(lp, col_name, FALSE);
				coeff[var_count] = get_f(this_task, i, j);
				var_count++;
			}			
		}
		if(!set_obj_fnex(lp, var_count, coeff, var))
			ret = 4;
		set_maxim(lp);
		write_LP(lp, stdout);
		set_verbose(lp, IMPORTANT);
		ret = solve(lp);
		if(ret == OPTIMAL)
			ret = 0;
		else
			ret = 5;
	}
	if(ret == 0) {
		obj = get_objective(lp);
		/* Displaying calculated values */		
		/* variable values */
		printf("\nVariable values:\n");
		get_variables(lp, coeff);
		printf("\n");
		for(j = 0; j < numVar; j++)
			printf("%s: %f\n", get_col_name(lp, j + 1), coeff[j]);		
		/* objective value */
		printf("\nObjective value: %f\n\n", obj);
	}
	printf("LP ERROR = %d\n\n", ret);
	
	/* free allocated memory */
	if(coeff != NULL)
		free(coeff);
	if(var != NULL)
		free(var);
	if(lp != NULL) 		
		delete_lp(lp);
	
	return ret == 0 ? obj : 0;
}
Ejemplo n.º 8
0
/* main() for udpxrec module
 */
int udpxrec_main( int argc, char* const argv[] )
{
    int rc = 0, ch = 0, custom_log = 0, no_daemon = 0;
    static const char OPTMASK[] = "vb:e:M:p:B:n:m:l:c:R:u:T";
    time_t now = time(NULL);
    char now_buf[ 32 ] = {0}, sel_buf[ 32 ] = {0}, app_finfo[80] = {0};

    extern int optind, optopt;
    extern const char IPv4_ALL[];

    mk_app_info(g_udpxrec_app, g_app_info, sizeof(g_app_info) - 1);

    if( argc < 2 ) {
        usage( argv[0], stderr );
        return ERR_PARAM;
    }

    rc = init_recopt( &g_recopt );
    while( (0 == rc) && (-1 != (ch = getopt( argc, argv, OPTMASK ))) ) {
        switch(ch) {
            case 'T':   no_daemon = 1; break;
            case 'v':   set_verbose( &g_recopt.is_verbose ); break;
            case 'b':
                        if( (time_t)0 != g_recopt.end_time ) {
                            (void) fprintf( stderr, "Cannot specify start-recording "
                                    "time after end-recording time has been set\n" );
                        }

                        rc = a2time( optarg, &g_recopt.bg_time, time(NULL) );
                        if( 0 != rc ) {
                            (void) fprintf( stderr, "Invalid time: [%s]\n", optarg );
                            rc = ERR_PARAM;
                        }
                        else {
                            if( g_recopt.bg_time < now ) {
                                (void)strncpy( now_buf, Zasctime(localtime( &now )),
                                        sizeof(now_buf) );
                                (void)strncpy( sel_buf,
                                        Zasctime(localtime( &g_recopt.bg_time )),
                                        sizeof(sel_buf) );

                                (void) fprintf( stderr,
                                        "Selected %s time is in the past, "
                                        "now=[%s], selected=[%s]\n", "start",
                                        now_buf, sel_buf );
                                rc = ERR_PARAM;
                            }
                        }

                        break;
            case 'e':
                        if( (time_t)0 == g_recopt.bg_time ) {
                            g_recopt.bg_time = time(NULL);
                            (void)fprintf( stderr,
                                    "Start-recording time defaults to now [%s]\n",
                                    Zasctime( localtime( &g_recopt.bg_time ) ) );
                        }

                        rc = a2time( optarg, &g_recopt.end_time, g_recopt.bg_time );
                        if( 0 != rc ) {
                            (void) fprintf( stderr, "Invalid time: [%s]\n", optarg );
                            rc = ERR_PARAM;
                        }
                        else {
                            if( g_recopt.end_time < now ) {
                                (void)strncpy( now_buf, Zasctime(localtime( &now )),
                                        sizeof(now_buf) );
                                (void)strncpy( sel_buf,
                                        Zasctime(localtime( &g_recopt.end_time )),
                                        sizeof(sel_buf) );

                                (void) fprintf( stderr,
                                        "Selected %s time is in the past, "
                                        "now=[%s], selected=[%s]\n", "end",
                                        now_buf, sel_buf );
                                rc = ERR_PARAM;
                            }
                        }
                        break;

            case 'M':
                        rc = a2int64( optarg, &g_recopt.max_fsize );
                        if( 0 != rc ) {
                            (void) fprintf( stderr, "Invalid file size: [%s]\n",
                                    optarg );
                            rc = ERR_PARAM;
                        }
                        break;
            case 'p':
                        g_recopt.pidfile = strdup(optarg);
                        break;

            case 'B':
                        rc = a2size( optarg, &g_recopt.bufsize );
                        if( 0 != rc ) {
                            (void) fprintf( stderr, "Invalid buffer size: [%s]\n",
                                    optarg );
                            rc = ERR_PARAM;
                        }
                        else if( (g_recopt.bufsize < MIN_MCACHE_LEN) ||
                                 (g_recopt.bufsize > MAX_MCACHE_LEN)) {
                            (void) fprintf( stderr,
                                "Buffer size must be in [%ld-%ld] bytes range\n",
                                (long)MIN_MCACHE_LEN, (long)MAX_MCACHE_LEN );
                            rc = ERR_PARAM;
                        }

                        break;
            case 'n':
                      g_recopt.nice_incr = atoi( optarg );
                      if( 0 == g_recopt.nice_incr ) {
                        (void) fprintf( stderr,
                            "Invalid nice-value increment: [%s]\n", optarg );
                        rc = ERR_PARAM;
                      }
                      break;
            case 'm':
                      rc = get_ipv4_address( optarg, g_recopt.mcast_addr,
                              sizeof(g_recopt.mcast_addr) );
                      if( 0 != rc ) {
                        (void) fprintf( stderr, "Invalid multicast address: [%s]\n",
                                        optarg );
                          rc = ERR_PARAM;
                      }
                      break;
            case 'l':
                      g_flog = fopen( optarg, "a" );
                      if( NULL == g_flog ) {
                        rc = errno;
                        (void) fprintf( stderr, "Error opening logfile [%s]: %s\n",
                                optarg, strerror(rc) );
                        rc = ERR_PARAM; break;
                      }

                      Setlinebuf( g_flog );
                      custom_log = 1;
                      break;

            case 'c':
                      rc = get_addrport( optarg, g_recopt.rec_channel,
                                         sizeof( g_recopt.rec_channel ),
                                         &g_recopt.rec_port );
                      if( 0 != rc ) rc = ERR_PARAM;
                      break;

            case 'R':
                      g_recopt.rbuf_msgs = atoi( optarg );
                      if( (g_recopt.rbuf_msgs <= 0) && (-1 != g_recopt.rbuf_msgs) ) {
                        (void) fprintf( stderr,
                                "Invalid rcache size: [%s]\n", optarg );
                        rc = ERR_PARAM;
                      }
                      break;

            case 'u':
                      g_recopt.waitupd_sec = atoi(optarg);
                      if( g_recopt.waitupd_sec <= 0 ) {
                          (void) fprintf( stderr, "Invalid wait-update value [%s] "
                                  "(must be a number > 0)\n", optarg );
                          rc = ERR_PARAM;
                      }
                      break;

            case ':':
                      (void) fprintf( stderr, "Option [-%c] requires an argument\n",
                              optopt );
                      rc = ERR_PARAM; break;
            case '?':
                      (void) fprintf( stderr, "Unrecognized option: [-%c]\n", optopt );
                      rc = ERR_PARAM; break;
            default:
                      usage( argv[0], stderr );
                      rc = ERR_PARAM; break;

        } /* switch */
    } /* while getopt */

    if( 0 == rc ) {
        if( optind >= argc ) {
            (void) fputs( "Missing destination file parameter\n", stderr );
            rc = ERR_PARAM;
        }
        else {
            g_recopt.dstfile = strdup( argv[optind] );
        }

        if( !(g_recopt.max_fsize > 0 || g_recopt.end_time)  ) {
            (void) fputs( "Must specify either max file [-M] size "
                    "or end time [-e]\n", stderr );
            rc = ERR_PARAM;
        }

        if( !g_recopt.rec_channel[0] || !g_recopt.rec_port ) {
            (void) fputs( "Must specify multicast channel to record from\n",
                    stderr );
            rc = ERR_PARAM;
        }
    }

    if( rc ) {
        free_recopt( &g_recopt );
        return rc;
    }

    do {
        if( '\0' == g_recopt.mcast_addr[0] ) {
            (void) strncpy( g_recopt.mcast_addr, IPv4_ALL,
                    sizeof(g_recopt.mcast_addr) - 1 );
        }

        if( !custom_log ) {
            /* in debug mode output goes to stderr, otherwise to /dev/null */
            g_flog = ((uf_TRUE == g_recopt.is_verbose)
                    ? stderr
                    : fopen( "/dev/null", "a" ));
            if( NULL == g_flog ) {
                perror("fopen");
                rc = ERR_INTERNAL; break;
            }
        }

        if( 0 == geteuid() ) {
            if( !no_daemon ) {
                if( stderr == g_flog ) {
                    (void) fprintf( stderr,
                        "Logfile must be specified to run "
                        "in verbose mode in background\n" );
                    rc = ERR_PARAM; break;
                }

                if( NULL == g_recopt.pidfile ) {
                    (void) fprintf( stderr, "pidfile must be specified "
                            "to run as daemon\n" );
                    rc = ERR_PARAM; break;
                }

                if( 0 != (rc = daemonize(0, g_flog)) ) {
                    rc = ERR_INTERNAL; break;
                }
            }

        } /* 0 == geteuid() */

        if( NULL != g_recopt.pidfile ) {
            rc = make_pidfile( g_recopt.pidfile, getpid(), g_flog );
            if( 0 != rc ) break;
        }

        (void) set_nice( g_recopt.nice_incr, g_flog );

        if( 0 != (rc = setup_signals()) ) break;

        TRACE( fprint_recopt( g_flog, &g_recopt ) );

        TRACE( printcmdln( g_flog, g_app_info, argc, argv ) );

        if( g_recopt.bg_time ) {
            if( 0 != (rc = verify_channel()) || g_quit )
                break;

            rc = wait_till( g_recopt.bg_time, g_recopt.waitupd_sec );
            if( rc || g_quit ) break;
        }

        rc = record();

        if( NULL != g_recopt.pidfile ) {
            if( -1 == unlink(g_recopt.pidfile) ) {
                mperror( g_flog, errno, "unlink [%s]", g_recopt.pidfile );
            }
        }
    }
    while(0);

    if( g_flog ) {
        (void)tmfprintf( g_flog, "%s is exiting with rc=[%d]\n",
                app_finfo, rc );
    }

    if( g_flog && (stderr != g_flog) ) {
        (void) fclose(g_flog);
    }

    free_recopt( &g_recopt );

    return rc;
}
Ejemplo n.º 9
0
int main(int argc, char **args)
{
	set_verbose(false);

	if (argc < 3) error("Not enough parameters");

	char *type = args[1];

	Mesh mesh;
	Mesh3DReader mesh_loader;
	if (!mesh_loader.load(args[2], &mesh)) error("Loading mesh file '%s'\n", args[2]);

	if (strcmp(type, "sln") == 0) {
		// Testing on Exact solution which always gives the same value (values from Solution may differ by epsilon)
		ExactSolution ex_sln(&mesh, exact_solution);
		output.out(&ex_sln, "U");
	}
	else if (strcmp(type, "vec-sln") == 0) {
		// Testing on Exact solution which always gives the same value (values from Solution may differ by epsilon)
		ExactSolution ex_sln(&mesh, exact_vec_solution);
		output.out(&ex_sln, "U");
	}
	else if (strcmp(type, "3sln") == 0) {
		// Testing on Exact solution which always gives the same value (values from Solution may differ by epsilon)
		ExactSolution ex_sln0(&mesh, exact_solution0);
		ExactSolution ex_sln1(&mesh, exact_solution1);
		ExactSolution ex_sln2(&mesh, exact_solution2);
		output.out(&ex_sln0, &ex_sln1, &ex_sln2, "U");
	}
	else if (strcmp(type, "ord") == 0) {
		H1ShapesetLobattoHex shapeset;

		H1Space space(&mesh, &shapeset);
		space.set_bc_types(bc_types);
		space.set_essential_bc_values(essential_bc_values);

		order3_t order;
		if (mesh.elements[1]->get_mode() == MODE_HEXAHEDRON)
			order = order3_t(2, 3, 4);
		else if (mesh.elements[1]->get_mode() == MODE_TETRAHEDRON)
			order = order3_t(3);
		else
			error(H3D_ERR_NOT_IMPLEMENTED);
		space.set_uniform_order(order);

		output.out_orders(&space, "orders");
	}
	else if (strcmp(type, "bc") == 0) {
		output.out_bc(&mesh);
	}
	else if (strcmp(type, "mat") == 0) {
		StiffMatrix mat;
		test_mat(&mesh, mat);
		output.out(&mat);
	}
	else if (strcmp(type, "mm") == 0) {
		test_mm(&mesh);
	}

	return 0;
}
Ejemplo n.º 10
0
    int  calculate (IN  int nCols /* variables in the model */,
                    IN  int nRows,
                    IN  double** rows,
                    IN  double*  rights,
                    IN  double*  objectives,
                    OUT int* answer,
                    IN  int verbose)
    {
      lprec *lp;
      int result = 0;

      char *str = NULL;
      int *colno = NULL;
      double *row = NULL;

      /*  We will build the model row by row
       *  So we start with creating a model
       *  with 0 rows and 2 columns
       */
      if ( !(lp = make_lp (0, nCols)) )
      { 
        /* couldn't construct a new model... */
        result = 1;
        goto RESULT;
      }

      if ( !(str = (char*) malloc ((log10 (nCols) + 10) * sizeof (*str))) )
      {
        result = 2;
        goto RESULT;
      }

      /*  let us name our variables. Not required, 
       *  but can be useful for debugging
       */
      for ( int i = 1; i <= nCols; ++i )
      {       
        str[0] = 't';
        _itoa (i, str + 1, 10);

        set_col_name (lp, i, str);
        // set_int (lp, i, TRUE);
      }

      /* create space large enough for one row */
      colno = (int   *) malloc (nCols * sizeof (*colno));
      row   = (double*) malloc (nCols * sizeof (*row));

      if ( (colno == NULL) || (row == NULL) )
      {
        result = 2;
        goto RESULT;
      }

      for ( int j = 0; j < nCols; ++j )
      { colno[j] = j + 1; /* (j + 1) column */ }

      /* makes building the model faster if it is done rows by row */
      set_add_rowmode (lp, TRUE);
      
      for ( int i = 0; i < nRows; ++i )
      {
        // /* construct j row */
        // for ( int j = 0; j < nCols; ++j )
        // { row[j] = ??? ; }

        /* (210 * t2 + 156 * t3 == 0.0178) */
        /* (230 * t2 + 160 * t3 == 0.0176) */

        /* add the row to lp_solve */
        if ( !add_constraintex (lp, nCols, rows[i], colno, EQ, rights[i]) )
        {
          result = 3;
          goto RESULT;
        }
      }

      /* rowmode should be turned off again when done building the model */
      set_add_rowmode (lp, FALSE); 

      // /* set the objective function  */
      // for ( int j = 0; j < nCols; ++j )
      // { row[j] = objectives[j]; }

      /* (t1 + t2 + t3 + t4) */

      /* set the objective in lp_solve */
      if ( !set_obj_fnex (lp, nCols, objectives, colno) )
      {
        result = 4;
        goto RESULT;
      }
      
      /* set the object direction to maximize */
      set_minim (lp);

      if ( verbose )
      {
        /* just out of curioucity, now show the model in lp format on screen */
        /* this only works if this is a console application. If not, use write_lp and a filename */
        write_LP (lp, stdout);
        /* write_lp(lp, "model.lp"); */
      }
      
      /* I only want to see important messages on screen while solving */
      set_verbose (lp, IMPORTANT);
      
      /* Now let lpsolve calculate a solution */
      result = solve (lp);
      if ( result == OPTIMAL )
      { result = 0; }
      else
      {
        result = 5;
        goto RESULT;
      }

      /*  a solution is calculated,
       *  now lets get some results
       */
      if ( verbose )
      {
        /* objective value */
        printf ("Objective value: %f\n", get_objective (lp));
      }

      /* variable values */
      get_variables (lp, row);
      for ( int j = 0; j < nCols; j++ )
      {
        if ( verbose )
          printf ("%s: %f\n", get_col_name (lp, j + 1), row[j]);
        
        answer[j] = row[j];
      }
      /* we are done now */

RESULT:;
      /* free allocated memory */
      if ( str != NULL )free (str);
      if ( row != NULL ) free (row);
      if ( colno != NULL ) free (colno);

      if ( lp != NULL )
      {
        /* clean up such that all used memory by lpsolve is freed */
        delete_lp (lp);
      }

      return result;
    }
Ejemplo n.º 11
0
int demo()
{
    lprec *lp;
    int Ncol, *colno = NULL, j, ret = 0;
    REAL *row = NULL;

    /* We will build the model row by row
       So we start with creating a model with 0 rows and 2 columns */
    Ncol = 2; /* there are two variables in the model */
    lp = make_lp(0, Ncol);
    if(lp == NULL)
        ret = 1; /* couldn't construct a new model... */

    if(ret == 0) {
        /* let us name our variables. Not required, but can be useful for debugging */
        set_col_name(lp, 1, "x");
        set_col_name(lp, 2, "y");

        /* create space large enough for one row */
        colno = (int *) malloc(Ncol * sizeof(*colno));
        row = (REAL *) malloc(Ncol * sizeof(*row));
        if((colno == NULL) || (row == NULL))
            ret = 2;
    }

    if(ret == 0) {
        set_add_rowmode(lp, TRUE);  /* makes building the model faster if it is done rows by row */

        /* construct first row (120 x + 210 y <= 15000) */
        j = 0;

        colno[j] = 1; /* first column */
        row[j++] = 120;

        colno[j] = 2; /* second column */
        row[j++] = 210;

        /* add the row to lpsolve */
        if(!add_constraintex(lp, j, row, colno, LE, 15000))
            ret = 3;
    }

    if(ret == 0) {
        /* construct second row (110 x + 30 y <= 4000) */
        j = 0;

        colno[j] = 1; /* first column */
        row[j++] = 110;

        colno[j] = 2; /* second column */
        row[j++] = 30;

        /* add the row to lpsolve */
        if(!add_constraintex(lp, j, row, colno, LE, 4000))
            ret = 3;
    }

    if(ret == 0) {
        /* construct third row (x + y <= 75) */
        j = 0;

        colno[j] = 1; /* first column */
        row[j++] = 1;

        colno[j] = 2; /* second column */
        row[j++] = 1;

        /* add the row to lpsolve */
        if(!add_constraintex(lp, j, row, colno, LE, 75))
            ret = 3;
    }

    if(ret == 0) {
        set_add_rowmode(lp, FALSE); /* rowmode should be turned off again when done building the model */

        /* set the objective function (143 x + 60 y) */
        j = 0;

        colno[j] = 1; /* first column */
        row[j++] = 143;

        colno[j] = 2; /* second column */
        row[j++] = 60;

        /* set the objective in lpsolve */
        if(!set_obj_fnex(lp, j, row, colno))
            ret = 4;
    }

    if(ret == 0) {
        /* set the object direction to maximize */
        set_maxim(lp);

        /* just out of curioucity, now show the model in lp format on screen */
        /* this only works if this is a console application. If not, use write_lp and a filename */
        write_LP(lp, stdout);
        /* write_lp(lp, "model.lp"); */

        /* I only want to see important messages on screen while solving */
        set_verbose(lp, IMPORTANT);

        /* Now let lpsolve calculate a solution */
        ret = solve(lp);
        if(ret == OPTIMAL)
            ret = 0;
        else
            ret = 5;
    }

    if(ret == 0) {
        /* a solution is calculated, now lets get some results */

        /* objective value */
        printf("Objective value: %f\n", get_objective(lp));

        /* variable values */
        get_variables(lp, row);
        for(j = 0; j < Ncol; j++)
            printf("%s: %f\n", get_col_name(lp, j + 1), row[j]);

        /* we are done now */
    }

    /* free allocated memory */
    if(row != NULL)
        free(row);
    if(colno != NULL)
        free(colno);

    if(lp != NULL) {
        /* clean up such that all used memory by lpsolve is freed */
        delete_lp(lp);
    }

    return(ret);
}
Ejemplo n.º 12
0
/**
 * A simple JIRA plugin client for development purposes only.
 */
int main(int argc, char **argv)
 {
    int opt,test_case = -1;
    bool verbose_flag = false;
    gchar *jira_cfg_path = "jira.cfg";
    gchar *json_path = NULL;
    autofree(gchar) *jira_issues_json = NULL;
    autofree(gchar) *jira_json = NULL;
    autofree(gchar) *summary = NULL;
    autofree(gchar) *description = g_strdup("This is just a test. Ignore");
    GHashTable *jira_issues = NULL;
    GSList *jira_issues_list = NULL;

    time_t now = time(NULL);

    while ((opt = getopt(argc,argv,"c:ht:V")) != -1)
        switch(opt) {
            case 'c':
                jira_cfg_path = argv[optind-1];
                break;
            case 't':
                test_case = atoi(argv[optind-1]);
                break;
            case 'V':
                verbose_flag = true;
                break;
            case 'h':
                show_usage(argv[0]);
                return 0;
        }
    if (test_case < 0) {
        show_usage(argv[0]);
        return -1;
    }
    printf("\n[Execute: test case %i using %s]\n\n", test_case, jira_cfg_path);
    if (!init_jira_plugin(NULL, jira_cfg_path)) return 1;
    set_verbose(verbose_flag);
    switch(test_case) {
        /* Check if JIRA server is responsive */
        case 1:
            if (!is_jira_alive())
                goto cleanup;
            break;
        /* Do a simple query */
        case 2:
            if (!is_jira_alive())
                goto cleanup;
            if (!build_search_jira_issues(&jira_json))
                 goto cleanup;
            if (!search_jira_issues(jira_json, &jira_issues_json))
                goto cleanup;
            if (!parse_jira_issues(jira_issues_json, &jira_issues_list))
                goto cleanup;
            show_jira_issues_list(jira_issues_list);
            if (!save_jira_issues_csv(
                jira_issues_list,"jira_test2_results.csv"))
                goto cleanup;
            if (!save_jira_issues_xml(jira_issues_list,
                "jira_test2_results.xml"))
                goto cleanup;
            if (!save(jira_json, "jira_test2_json.txt"))
                goto cleanup;
            if (!save(jira_issues_json, "jira_test2_issues_json.txt"))
                goto cleanup;
            free_jira_issues_list(&jira_issues_list);
            break;
        /* Add a new JIRA issue */
        case 3:
            if (!is_jira_alive())
                goto cleanup;
            summary =
            g_strdup_printf("CVE-%s (Test:3)", g_strstrip(ctime(&now)));
            if (!build_new_jira_issue(summary, description, false, &jira_json))
                goto cleanup;
            printf("Adding new JIRA issue: [%s]\n", summary);
            if (!add_new_jira_issue(jira_json))
                goto cleanup;
            g_free(jira_json);
            if (!build_search_jira_issues(&jira_json))
                 goto cleanup;
            if (!search_jira_issues(jira_json, &jira_issues_json))
                goto cleanup;
            if (!parse_jira_issues(jira_issues_json, &jira_issues_list))
                goto cleanup;
            show_jira_issues_list(jira_issues_list);
            if (!save_jira_issues_csv(
                jira_issues_list,"jira_test3_results_add.csv"))
                goto cleanup;
            if (!save_jira_issues_xml(
                jira_issues_list,"jira_test3_results_add.xml"))
                goto cleanup;
            free_jira_issues_list(&jira_issues_list);
            break;
        /* Add a new issue using a self-generated template */
        case 4:
            summary =
            g_strdup_printf("CVE-%s (Test:4)", g_strstrip(ctime(&now)));
            if (!build_new_jira_issue(NULL, NULL, true, &jira_json))
                goto cleanup;
            json_path = "jira_test4_results_template_raw.json";
            if (!save(jira_json, json_path))
                goto cleanup;
            g_free(jira_json);
            if (!build_new_jira_issue_file(
                json_path, summary, description, &jira_json))
                goto cleanup;
            json_path = "jira_test4_results_template_resolved.json";
            if (!save(jira_json, json_path))
                goto cleanup;
            if (!add_new_jira_issue(jira_json))
                goto cleanup;
            g_free(jira_json);
            if (!build_search_jira_issues(&jira_json))
                 goto cleanup;
            if (!search_jira_issues(jira_json, &jira_issues_json))
                goto cleanup;
            if (!parse_jira_issues(jira_issues_json, &jira_issues_list))
                goto cleanup;
            show_jira_issues_list(jira_issues_list);
            if (!save_jira_issues_csv(
                jira_issues_list,"jira_test4_results_add.csv"))
                goto cleanup;
            if (!save_jira_issues_xml(
                jira_issues_list,"jira_test4_results_add.xml"))
                goto cleanup;
            free_jira_issues_list(&jira_issues_list);
            break;
        case 5:
            summary =
            g_strdup_printf("CVE-%s (Test:5)", g_strstrip(ctime(&now)));
            if (!build_search_jira_issues(&jira_json)) {
                return false;
            }
            if (!get_jira_issues(jira_json, &jira_issues)) {
                return false;
            }
            show_jira_issues(jira_issues);
            free_jira_issues(&jira_issues);
            break;
        default:
            show_usage(argv[0]);
            printf("Error: Unknown test case: %i\n", test_case);
            break;
    }
    printf("Test passed!\n\n");
    destroy_jira_plugin();
    return 0;
cleanup:
    printf("Test failed!\n\n");
    destroy_jira_plugin();
    return 1;
}
Ejemplo n.º 13
0
int
main(int argc, char *argv[])
{
	struct radclock_handle *handle;
	struct radclock_config *conf;
	int is_daemon = 0;

	/* File and command line reading */
	int ch;
	
	/* Mask variable used to know which parameter to update */
	uint32_t param_mask = 0;

	/* PID lock file for daemon */
	int daemon_pid_fd 		= 0;

	/* Initialize PID lockfile to a default value */
	const char *pid_lockfile = DAEMON_LOCK_FILE;

	/* Misc */
	int err;

	/* turn off buffering to allow results to be seen immediately if JDEBUG*/
	#ifdef WITH_JDEBUG
	setvbuf(stdout, (char *)NULL, _IONBF, 0);
	setvbuf(stderr, (char *)NULL, _IONBF, 0);
	#endif

	/*
	 * Register Signal handlers. We use sigaction() instead of signal() to catch
	 * signals. The main reason concerns the SIGHUP signal. In Linux, the
	 * syscalls are restarted as soon as the signal handler returns. This
	 * prevent pcap_breakloop() to do its job (see pcap man page). Using
	 * sigaction() we can overwrite the default flag to prevent this behavior
	 */
	sigset_t block_mask;
	sigfillset (&block_mask);
	struct sigaction sig_struct;


	sig_struct.sa_handler = signal_handler;
	sig_struct.sa_mask = block_mask;
	sig_struct.sa_flags = 0;

	sigaction(SIGHUP,  &sig_struct, NULL); /* hangup signal (1) */
	sigaction(SIGTERM, &sig_struct, NULL); /* software termination signal (15) */
	sigaction(SIGUSR1, &sig_struct, NULL); /* user signal 1 (30) */
	sigaction(SIGUSR2, &sig_struct, NULL); /* user signal 2 (31) */


	/* Initialise verbose data to defaults */
	verbose_data.handle = NULL;
	verbose_data.is_daemon = 0;
	verbose_data.verbose_level = 0;
	verbose_data.fd = NULL;
	strcpy(verbose_data.logfile, "");
	pthread_mutex_init(&(verbose_data.vmutex), NULL);


	/* Management of configuration options */
	conf = (struct radclock_config *) malloc(sizeof(struct radclock_config));
	JDEBUG_MEMORY(JDBG_MALLOC, conf);
	memset(conf, 0, sizeof(struct radclock_config));

	/*
	 * The command line arguments are given the priority and override possible
	 * values of the configuration file But the configuration file is parsed
	 * after the command line because we need to know if we are running a daemon
	 * or not (configuration file is different if we run a daemon or not). Use
	 * the param_mask variable to indicate which values have to be updated from
	 * the config file
	 */

	/* Initialize the physical parameters, and other config parameters. */
	config_init(conf);

	/* Init the mask we use to signal configuration updates */
	param_mask = UPDMASK_NOUPD;

	/* Reading the command line arguments */
	while ((ch = getopt(argc, argv, "dxvhc:i:l:n:t:r:w:s:a:o:p:P:U:D:V")) != -1)
		switch (ch) {
		case 'x':
			SET_UPDATE(param_mask, UPDMASK_SERVER_IPC);
			conf->server_ipc = BOOL_OFF;
			break;
		case 'c':
			strcpy(conf->conffile, optarg);
			break;
		case 'd':
			is_daemon = 1;
			break;
		case 'l':
			strcpy(conf->logfile, optarg);
			break;
		case 'n':
			if (strlen(optarg) > MAXLINE) {
				fprintf(stdout, "ERROR: parameter too long\n");
				exit (1);
			}
			SET_UPDATE(param_mask, UPDMASK_HOSTNAME);
			strcpy(conf->hostname, optarg);
			break;
		case 'p':
			SET_UPDATE(param_mask, UPDMASK_POLLPERIOD);
			if ( atoi(optarg) < RAD_MINPOLL ) {
				conf->poll_period = RAD_MINPOLL;
				fprintf(stdout, "Warning: Poll period too small, set to %d\n",
					conf->poll_period);
			}
			else
				conf->poll_period = atoi(optarg);
			if ( conf->poll_period > RAD_MAXPOLL ) {
				conf->poll_period = RAD_MAXPOLL;
				fprintf(stdout, "Warning: Poll period too big, set to %d\n",
						conf->poll_period);
			}
			break;
		case 't':
			if (strlen(optarg) > MAXLINE) {
				fprintf(stdout, "ERROR: parameter too long\n");
				exit (1);
			}
			SET_UPDATE(param_mask, UPDMASK_TIME_SERVER);
			strcpy(conf->time_server, optarg);
			break;
		case 'i':
			if (strlen(optarg) > MAXLINE) {
				fprintf(stdout, "ERROR: parameter too long\n");
				exit (1);
			}
			SET_UPDATE(param_mask, UPDMASK_NETWORKDEV);
			strcpy(conf->network_device, optarg);
			break;
		case 'r':
			if (strlen(optarg) > MAXLINE) {
				fprintf(stdout, "ERROR: parameter too long\n");
				exit (1);
			}
			SET_UPDATE(param_mask, UPDMASK_SYNC_IN_PCAP);
			strcpy(conf->sync_in_pcap, optarg);
			break;
		case 'w':
			if (strlen(optarg) > MAXLINE) {
				fprintf(stdout, "ERROR: parameter too long\n");
				exit (1);
			}
			SET_UPDATE(param_mask, UPDMASK_SYNC_OUT_PCAP);
			strcpy(conf->sync_out_pcap, optarg);
			break;
		case 's':
			if (strlen(optarg) > MAXLINE) {
				fprintf(stdout, "ERROR: parameter too long\n");
				exit (1);
			}
			SET_UPDATE(param_mask, UPDMASK_SYNC_IN_ASCII);
			strcpy(conf->sync_in_ascii, optarg);
			break;
		case 'a':
			if (strlen(optarg) > MAXLINE) {
				fprintf(stdout, "ERROR: parameter too long\n");
				exit (1);
			}
			SET_UPDATE(param_mask, UPDMASK_SYNC_OUT_ASCII);
			strcpy(conf->sync_out_ascii, optarg);
			break;
		case 'o':
			if (strlen(optarg) > MAXLINE) {
				fprintf(stdout, "ERROR: parameter too long\n");
				exit (1);
			}
			SET_UPDATE(param_mask, UPDMASK_CLOCK_OUT_ASCII);
			strcpy(conf->clock_out_ascii, optarg);
			break;
		case 'P':
			if (strlen(optarg) > MAXLINE) {
				fprintf(stdout, "ERROR: parameter too long\n");
				exit (1);
			}
			SET_UPDATE(param_mask, UPDMASK_PID_FILE);
			pid_lockfile = optarg;
			break;
		case 'v':
			SET_UPDATE(param_mask, UPDMASK_VERBOSE);
			conf->verbose_level++;
			break;
		case 'U':
			SET_UPDATE(param_mask, UPD_NTP_UPSTREAM_PORT);
			conf->ntp_upstream_port = atoi(optarg);
			break;
		case 'D':
			SET_UPDATE(param_mask, UPD_NTP_DOWNSTREAM_PORT);
			conf->ntp_downstream_port = atoi(optarg);
			break;
		case 'V':
			fprintf(stdout, "%s version %s\n", PACKAGE_NAME, PACKAGE_VERSION);
		case 'h':
		case '?':
		default:
			usage();
		}

	argc -= optind;
	argv += optind;

	/* Little hack to deal with parsing of long options in the command line */
	if (conf->verbose_level > 0)
		SET_UPDATE(param_mask, UPDMASK_VERBOSE);


	/* Create the radclock handle */
	clock_handle = create_handle(conf, is_daemon);
	if (!clock_handle) {
		verbose(LOG_ERR, "Could not create clock handle");
		return (-1);
	}
	handle = clock_handle;


	/*
	 * Have not parsed the config file yet, so will have to do it again since it
	 * may not be the right settings. Handles config parse messages in the right
	 * log file though. So far clock has not been sent to init, no syscall
	 * registered, pass a NULL pointer to verbose.
	 */
	set_verbose(handle, handle->conf->verbose_level, 0);
	set_logger(logger_verbose_bridge);
	
	/* Daemonize now, so that we can open the log files and close connection to
	 * stdin since we parsed the command line
	 */
	if (handle->is_daemon) {
		struct stat sb;
		if (stat(RADCLOCK_RUN_DIRECTORY, &sb) < 0) {
			if (mkdir(RADCLOCK_RUN_DIRECTORY, 0755) < 0) {
				verbose(LOG_ERR, "Cannot create %s directory. Run as root or "
						"(!daemon && !server)", RADCLOCK_RUN_DIRECTORY);
				return (1);
			}
		}
		/* Check this everytime in case something happened */
		chmod(RADCLOCK_RUN_DIRECTORY, 00755);

		if (!(daemonize(pid_lockfile, &daemon_pid_fd))) {
			fprintf(stderr, "Error: did not manage to create the daemon\n");
			exit(EXIT_FAILURE);
		}
	}

	/*
	 * Retrieve configuration from the config file (write it down if it does not
	 * exist) That should be the only occasion when get_config() is called and
	 * the param_mask is not positioned to UPDMASK_NOUPD !!!  Only the
	 * parameters not specified on the command line are updated
	 */
	if (!config_parse(handle->conf, &param_mask, handle->is_daemon))
		return (0);

	/*
	 * Now that we have the configuration to use (verbose level),  let's
	 * initialise the verbose level to correct value
	 */
	set_verbose(handle, handle->conf->verbose_level, 0);
	set_logger(logger_verbose_bridge);

	/* Check for incompatible configurations and correct them */
	if (( handle->conf->synchro_type == SYNCTYPE_SPY ) ||
		( handle->conf->synchro_type == SYNCTYPE_PIGGY ))
	{
		if (handle->conf->server_ntp == BOOL_ON) {
			verbose(LOG_ERR, "Configuration error. Disabling NTP server "
					"(incompatible with spy or piggy mode).");
			handle->conf->server_ntp = BOOL_OFF;
		}
		if ( handle->conf->adjust_sysclock == BOOL_ON )
		{
			verbose(LOG_ERR, "Configuration error. Disabling adjust system "
					"clock (incompatible with spy or piggy mode).");
			handle->conf->adjust_sysclock = BOOL_OFF;
		}
	}
	
	/* Diagnosis output for the configuration used */
	config_print(LOG_NOTICE, handle->conf);

	/* Reinit the mask that counts updated values */
	param_mask = UPDMASK_NOUPD;


	// TODO extract extra checks from is_live_source and make an input fix 
	// function instead, would be clearer
	// TODO the conf->network_device business is way too messy


	/*
	 * Need to know if we are replaying data or not. If not, no need to create
	 * shared global data on the system or open a BPF. This define input to the
	 * init of the radclock handle
	 */
	if (!is_live_source(handle))
		handle->run_mode = RADCLOCK_SYNC_DEAD;
	else
		handle->run_mode = RADCLOCK_SYNC_LIVE;

	/* Init clock handle and private data */
	if (handle->run_mode == RADCLOCK_SYNC_LIVE) {
		err = clock_init_live(handle->clock, &handle->rad_data);
		if (err) {
			verbose(LOG_ERR, "Could not initialise the RADclock");
			return (1);
		}
	}

	/* Init radclock specific stuff */
	err = init_handle(handle);
	if (err) {
		verbose(LOG_ERR, "Radclock process specific init failed.");
		return (1);
	}

	/*
	 * Now 2 cases. Either we are running live or we are replaying some data.
	 * If we run live, we will spawn some threads and do some smart things.  If
	 * we replay data, no need to do all of that, we access data and process it
	 * in the same thread.
	 */
	if (handle->run_mode == RADCLOCK_SYNC_DEAD) {

// TODO : manage peers better !!

		struct bidir_peer peer;
		/* Some basic initialisation which is required */
		init_peer_stamp_queue(&peer);
		peer.stamp_i = 0;
		// TODO XXX Need to manage peers better !!
		/* Register active peer */
		handle->active_peer = (void *)&peer;
		while (1) {
			err = process_rawdata(handle, &peer);
			if (err < 0)
				break;
		}

		destroy_peer_stamp_queue(&peer);
	}

	/*
	 * We loop in here in case we are rehashed. Threads are (re-)created every
	 * time we loop in
	 */
	else {
		while (err == 0) {
			err = start_live(handle);
			if (err == 0) {
				if (rehash_daemon(handle, param_mask))
					verbose(LOG_ERR, "SIGHUP - Failed to rehash daemon !!.");
			}
		}
	}


	// TODO: look into making the stats a separate structure. Could be much
	// TODO: easier to manage
	long int n_stamp;
	unsigned int ref_count;
	n_stamp = ((struct bidir_output *)handle->algo_output)->n_stamps;
	ref_count = ((struct stampsource*)(handle->stamp_source))->ntp_stats.ref_count;
	verbose(LOG_NOTICE, "%u NTP packets captured", ref_count);
	verbose(LOG_NOTICE,"%ld missed NTP packets", ref_count - 2 * n_stamp);
	verbose(LOG_NOTICE, "%ld valid timestamp tuples extracted", n_stamp);

	/* Close output files */
	close_output_stamp(handle);

	/* Print out last good phat value */
	verbose(LOG_NOTICE, "Last estimate of the clock source period: %12.10lg",
			RAD_DATA(handle)->phat);

	/* Say bye and close syslog */
	verbose(LOG_NOTICE, "RADclock stopped");
	if (handle->is_daemon)
		closelog ();
	unset_verbose();

	/* Free the lock file */
	if (handle->is_daemon) {
		write(daemon_pid_fd, "", 0);
		lockf(daemon_pid_fd, F_ULOCK, 0);
	}

	// TODO:  all the destructors have to be re-written
	destroy_source(handle, (struct stampsource *)(handle->stamp_source));


	/* Clear thread stuff */
	pthread_mutex_destroy(&(handle->globaldata_mutex));
	pthread_mutex_destroy(&(handle->wakeup_mutex));
	pthread_cond_destroy(&(handle->wakeup_cond));

	/* Detach IPC shared memory if were running as IPC server. */
	if (handle->conf->server_ipc == BOOL_ON)
		shm_detach(handle->clock);

	/* Free the clock structure. All done. */
	pthread_mutex_destroy(&(handle->pcap_queue->rdb_mutex));
	pthread_mutex_destroy(&(handle->ieee1588eq_queue->rdb_mutex));
	free(handle->pcap_queue);
	free(handle->ieee1588eq_queue);
	free(handle);
	handle = NULL;
	clock_handle = NULL;

	exit(EXIT_SUCCESS);
}
Ejemplo n.º 14
0
int main(int argc, char **argv)
{
	int res = ERR_SUCCESS;
	set_verbose(false);

	if (argc < 2) error("Not enough parameters");

	printf("* Loading mesh '%s'\n", argv[1]);
	Mesh mesh;
	H3DReader mesh_loader;
	if (!mesh_loader.load(argv[1], &mesh)) error("loading mesh file '%s'\n", argv[1]);

#if defined NONLIN1
	Ord3 order(1, 1, 1);
#else
	Ord3 order(2, 2, 2);
#endif
	printf("* Setting the space up\n");
	H1Space space(&mesh, bc_types, essential_bc_values, order);

	printf("  - Setting uniform order to (%d, %d, %d)\n", order.x, order.y, order.z);
	space.set_uniform_order(order);

	int ndofs = space.assign_dofs();
	printf("  - Number of DOFs: %d\n", ndofs);

#if defined NONLIN2
	// do L2 projection of zero function
	WeakForm proj_wf;
	proj_wf.add_matrix_form(biproj_form<double, scalar>, biproj_form<Ord, Ord>, SYM);
	proj_wf.add_vector_form(liproj_form<double, scalar>, liproj_form<Ord, Ord>);

	DiscreteProblem lp(&proj_wf, &space, true);

#ifdef WITH_UMFPACK
	UMFPackMatrix m;
	UMFPackVector v;
	UMFPackLinearSolver sl(&m, &v);
#elif defined WITH_MUMPS
	MumpsMatrix m;
	MumpsVector v;
	MumpsSolver sl(&m, &v);
#endif
	lp.assemble(&m, &v);
	sl.solve();

	double *ps = sl.get_solution();
#endif

	printf("* Calculating a solution\n");

	WeakForm wf(1);
	wf.add_matrix_form(0, 0, jacobi_form<double, scalar>, jacobi_form<Ord, Ord>, UNSYM);
	wf.add_vector_form(0, resid_form<double, scalar>, resid_form<Ord, Ord>);

	DiscreteProblem dp(&wf, &space, false);

	NoxSolver solver(&dp);
#if defined NONLIN2
	solver.set_init_sln(ps);
#endif
	solver.set_conv_iters(10);

	printf("  - solving..."); fflush(stdout);
	Timer solve_timer;
	solve_timer.start();
	bool solved = solver.solve();
	solve_timer.stop();

	if (solved) {
		printf(" done in %s (%lf secs), iters = %d\n", solve_timer.get_human_time(),
		       solve_timer.get_seconds(), solver.get_num_iters());

		double *s = solver.get_solution();
		Solution sln(&mesh);
		sln.set_coeff_vector(&space, s);

		Solution ex_sln(&mesh);
#ifdef NONLIN1
		ex_sln.set_const(100.0);
#else
		ex_sln.set_exact(exact_solution);
#endif
		double h1_err = h1_error(&sln, &ex_sln);
		printf("  - H1 error norm:      % le\n", h1_err);
		double l2_err = l2_error(&sln, &ex_sln);
		printf("  - L2 error norm:      % le\n", l2_err);

		if (h1_err > EPS || l2_err > EPS) {
			// calculated solution is not enough precise
			res = ERR_FAILURE;
		}
#ifdef OUTPUT_DIR
		printf("* Output\n");
		// output
		const char *of_name = OUTPUT_DIR "/solution.vtk";
		FILE *ofile = fopen(of_name, "w");
		if (ofile != NULL) {
			VtkOutputEngine output(ofile);
			output.out(&sln, "Uh", FN_VAL_0);
			fclose(ofile);
		}
		else {
			warning("Cann not open '%s' for writing.", of_name);
		}

#endif
	}
	else
		res = ERR_FAILURE;

	return res;
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
	_F_
	int ret = ERROR_SUCCESS;

	if (argc < 3) {
		fprintf(stderr, "ERROR: not enough parameters\n");
		return ERR_FAILURE;
	}

	if (strcmp(argv[1], "h1") != 0 && strcmp(argv[1], "h1-ipol")) {
		fprintf(stderr, "ERROR: unknown type of the projection\n");
		return ERR_FAILURE;
	}

#ifdef WITH_PETSC
	PetscInitialize(NULL, NULL, (char *) PETSC_NULL, PETSC_NULL);
#endif
	set_verbose(false);

	H1ShapesetLobattoHex shapeset;

	Mesh mesh;
	Mesh3DReader mloader;
	if (!mloader.load(argv[2], &mesh)) {
		fprintf(stderr, "ERROR: loading mesh file '%s'\n", argv[2]);
		return ERR_FAILURE;
	}

#if defined WITH_UMFPACK
	UMFPackMatrix mat;
	UMFPackVector rhs;
	UMFPackLinearSolver solver(&mat, &rhs);
#elif defined WITH_PARDISO
	PardisoMatrix mat;
	PardisoVector rhs;
	PardisoLinearSolver solver(&mat, &rhs);
#elif defined WITH_PETSC
	PetscMatrix mat;
	PetscVector rhs;
	PetscLinearSolver solver(&mat, &rhs);
#elif defined WITH_MUMPS
	MumpsMatrix mat;
	MumpsVector rhs;
	MumpsSolver solver(&mat, &rhs);
#endif

	Word_t ne = mesh.elements.count();
	// make the mesh for the ref. solution
	mesh.refine_all_elements(H3D_H3D_H3D_REFT_HEX_XYZ);

	H1Space space(&mesh, &shapeset);
	space.set_bc_types(bc_types);
	space.set_essential_bc_values(essential_bc_values);

#if defined X2_Y2_Z2
	order3_t o(2, 2, 2);
#elif defined X3_Y3_Z3
	order3_t o(3, 3, 3);
#elif defined XN_YM_ZO
	order3_t o(2, 3, 4);
#endif
	space.set_uniform_order(o);

	WeakForm wf;
	wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<ord_t, ord_t>, SYM, ANY);
	wf.add_vector_form(linear_form<double, scalar>, linear_form<ord_t, ord_t>, ANY);

	LinearProblem lp(&wf, &space);

	space.assign_dofs();

	// assemble the stiffness matrix
	lp.assemble(&mat, &rhs);

	// solve the stiffness matrix
	solver.solve();

	Solution sln(&mesh);
	sln.set_coeff_vector(&space, solver.get_solution());

	for (Word_t idx = mesh.elements.first(); idx <= ne; idx = mesh.elements.next(idx)) {
		Element *e = mesh.elements[idx];

		order3_t order(4, 4, 4);
		double error;

		Projection *proj;
		if (strcmp(argv[1], "h1") == 0) proj = new H1Projection(&sln, e, &shapeset);
		else if (strcmp(argv[1], "h1-ipol") == 0) proj = new H1ProjectionIpol(&sln, e, &shapeset);
		else return ERR_FAILURE;

		//
		error = 0.0;
		error += proj->get_error(H3D_REFT_HEX_NONE, -1, order);
		error = sqrt(error);
		CHECK_ERROR;

		//
		error = 0.0;
		error += proj->get_error(H3D_REFT_HEX_X, 20, order);
		error += proj->get_error(H3D_REFT_HEX_X, 21, order);
		error = sqrt(error);
		CHECK_ERROR;

		//
		error = 0.0;
		error += proj->get_error(H3D_REFT_HEX_Y, 22, order);
		error += proj->get_error(H3D_REFT_HEX_Y, 23, order);
		error = sqrt(error);
		CHECK_ERROR;

		//
		error = 0.0;
		error += proj->get_error(H3D_REFT_HEX_Z, 24, order);
		error += proj->get_error(H3D_REFT_HEX_Z, 25, order);
		error = sqrt(error);
		CHECK_ERROR;

		//
		error = 0.0;
		error += proj->get_error(H3D_H3D_REFT_HEX_XY,  8, order);
		error += proj->get_error(H3D_H3D_REFT_HEX_XY,  9, order);
		error += proj->get_error(H3D_H3D_REFT_HEX_XY, 10, order);
		error += proj->get_error(H3D_H3D_REFT_HEX_XY, 11, order);
		error = sqrt(error);
		CHECK_ERROR;

		//
		error = 0.0;
		error += proj->get_error(H3D_H3D_REFT_HEX_XZ, 12, order);
		error += proj->get_error(H3D_H3D_REFT_HEX_XZ, 13, order);
		error += proj->get_error(H3D_H3D_REFT_HEX_XZ, 14, order);
		error += proj->get_error(H3D_H3D_REFT_HEX_XZ, 15, order);
		error = sqrt(error);
		CHECK_ERROR;

		//
		error = 0.0;
		error += proj->get_error(H3D_H3D_REFT_HEX_YZ, 16, order);
		error += proj->get_error(H3D_H3D_REFT_HEX_YZ, 17, order);
		error += proj->get_error(H3D_H3D_REFT_HEX_YZ, 18, order);
		error += proj->get_error(H3D_H3D_REFT_HEX_YZ, 19, order);
		error = sqrt(error);
		CHECK_ERROR;

		//
		error = 0.0;
		for (int j = 0; j < 8; j++)
			error += proj->get_error(H3D_H3D_H3D_REFT_HEX_XYZ, j, order);
		error = sqrt(error);
		CHECK_ERROR;

		delete proj;
	}

#ifdef WITH_PETSC
	PetscFinalize();
#endif

	return ret;
}
Ejemplo n.º 16
0
int main(int argc, char **args) {
	int res = ERR_SUCCESS;

#ifdef WITH_PETSC
	PetscInitialize(&argc, &args, (char *) PETSC_NULL, PETSC_NULL);
#endif
	set_verbose(false);

	if (argc < 2) error("Not enough parameters");

	H1ShapesetLobattoHex shapeset;

	printf("* Loading mesh '%s'\n", args[1]);
	Mesh mesh;
	Mesh3DReader mesh_loader;
	if (!mesh_loader.load(args[1], &mesh)) error("Loading mesh file '%s'\n", args[1]);

	printf("* Setup space #1\n");
	H1Space space1(&mesh, &shapeset);
	space1.set_bc_types(bc_types);

	order3_t o1(2, 2, 2);
	printf("  - Setting uniform order to (%d, %d, %d)\n", o1.x, o1.y, o1.z);
	space1.set_uniform_order(o1);

	printf("* Setup space #2\n");
	H1Space space2(&mesh, &shapeset);
	space2.set_bc_types(bc_types);

	order3_t o2(4, 4, 4);
	printf("  - Setting uniform order to (%d, %d, %d)\n", o2.x, o2.y, o2.z);
	space2.set_uniform_order(o2);

	int ndofs = 0;
	ndofs += space1.assign_dofs();
	ndofs += space2.assign_dofs(ndofs);
	printf("  - Number of DOFs: %d\n", ndofs);

	printf("* Calculating a solution\n");

#if defined WITH_UMFPACK
	UMFPackMatrix mat;
	UMFPackVector rhs;
	UMFPackLinearSolver solver(&mat, &rhs);
#elif defined WITH_PARDISO
	PardisoMatrix mat;
	PardisoVector rhs;
	PardisoLinearSolver solver(&mat, &rhs);
#elif defined WITH_PETSC
	PetscMatrix mat;
	PetscVector rhs;
	PetscLinearSolver solver(&mat, &rhs);
#elif defined WITH_MUMPS
	MumpsMatrix mat;
	MumpsVector rhs;
	MumpsSolver solver(&mat, &rhs);
#endif

	WeakForm wf(2);
	wf.add_matrix_form(0, 0, bilinear_form_1_1<double, scalar>, bilinear_form_1_1<ord_t, ord_t>, SYM);
	wf.add_matrix_form(0, 1, bilinear_form_1_2<double, scalar>, bilinear_form_1_2<ord_t, ord_t>, SYM);
	wf.add_vector_form(0, linear_form_1<double, scalar>, linear_form_1<ord_t, ord_t>);

//	wf.add_biform(1, 0, bilinear_form_2_1<sfn_t, scalar>, bilinear_form_2_1<fn_order_t, ord_t>, SYM);
	wf.add_matrix_form(1, 1, bilinear_form_2_2<double, scalar>, bilinear_form_2_2<ord_t, ord_t>, SYM);
	wf.add_vector_form(1, linear_form_2<double, scalar>, linear_form_2<ord_t, ord_t>);

	LinearProblem lp(&wf);
	lp.set_spaces(Tuple<Space *>(&space1, &space2));

	// assemble stiffness matrix
	Timer assemble_timer("Assembling stiffness matrix");
	assemble_timer.start();
	lp.assemble(&mat, &rhs);
	assemble_timer.stop();

	// solve the stiffness matrix
	Timer solve_timer("Solving stiffness matrix");
	solve_timer.start();
	bool solved = solver.solve();
	solve_timer.stop();

	// output the measured values
	printf("%s: %s (%lf secs)\n", assemble_timer.get_name(), assemble_timer.get_human_time(), assemble_timer.get_seconds());
	printf("%s: %s (%lf secs)\n", solve_timer.get_name(), solve_timer.get_human_time(), solve_timer.get_seconds());

	mat.dump(stdout, "a");
	rhs.dump(stdout, "b");

	if (solved) {
		// solution 1
		Solution sln1(&mesh);
		sln1.set_coeff_vector(&space1, solver.get_solution());

		ExactSolution esln1(&mesh, exact_sln_fn_1);
		// norm
		double h1_sln_norm1 = h1_norm(&sln1);
		double h1_err_norm1 = h1_error(&sln1, &esln1);

		printf(" - H1 solution norm:   % le\n", h1_sln_norm1);
		printf(" - H1 error norm:      % le\n", h1_err_norm1);

		double l2_sln_norm1 = l2_norm(&sln1);
		double l2_err_norm1 = l2_error(&sln1, &esln1);
		printf(" - L2 solution norm:   % le\n", l2_sln_norm1);
		printf(" - L2 error norm:      % le\n", l2_err_norm1);

		if (h1_err_norm1 > EPS || l2_err_norm1 > EPS) {
			// calculated solution is not enough precise
			res = ERR_FAILURE;
		}

		// solution 2
		Solution sln2(&mesh);
		sln2.set_coeff_vector(&space2, solver.get_solution());

		ExactSolution esln2(&mesh, exact_sln_fn_2);
		// norm
		double h1_sln_norm2 = h1_norm(&sln2);
		double h1_err_norm2 = h1_error(&sln2, &esln2);

		printf(" - H1 solution norm:   % le\n", h1_sln_norm2);
		printf(" - H1 error norm:      % le\n", h1_err_norm2);

		double l2_sln_norm2 = l2_norm(&sln2);
		double l2_err_norm2 = l2_error(&sln2, &esln2);
		printf(" - L2 solution norm:   % le\n", l2_sln_norm2);
		printf(" - L2 error norm:      % le\n", l2_err_norm2);

		if (h1_err_norm2 > EPS || l2_err_norm2 > EPS) {
			// calculated solution is not enough precise
			res = ERR_FAILURE;
		}

#ifdef OUTPUT_DIR
		// output
		const char *of_name = OUTPUT_DIR "/solution.pos";
		FILE *ofile = fopen(of_name, "w");
		if (ofile != NULL) {
			GmshOutputEngine output(ofile);
			output.out(&sln1, "Uh_1");
			output.out(&esln1, "U1");
			output.out(&sln2, "Uh_2");
			output.out(&esln2, "U2");

			fclose(ofile);
		}
		else {
			warning("Can not open '%s' for writing.", of_name);
		}
#endif
	}

#ifdef WITH_PETSC
	mat.free();
	rhs.free();
	PetscFinalize();
#endif

	TRACE_END;

	return res;
}
Ejemplo n.º 17
0
vector<PathPoint *> LPPath :: findPath(vertex *curr) {
	lprec *lp;
	
	int numDropoff = 0;
	int numDropped = 0;
	int numPickup = 0;
	
	//find pairs for each dropoff point
	for(int i = 0; i < points.size(); i++) {
		if(points[i]->type == 1) {
			bool foundPair = false;
			
			for(int j = 0; j < points.size(); j++) {
				if(j != i && points[j]->pairIndex == points[i]->pairIndex) {
					pairIndex[i] = j;
					foundPair = true;
					break;
				}
			}
			
			//sometimes, there's an error and the pair cannot be found
			//in that case, print out some debugging information
			if(!foundPair) {
				cout << i << ":" << points[i]->pairIndex << "  ";
				for(int j = 0; j < points.size(); j++) {
					cout << points[j]->type << ":" << points[j]->pairIndex << " ";
				}
				cout << endl;
			}
		}
	}
	
	//occasionally we encounter a model that takes hours or days to solve
	//we set a timeout on the solve function, and then advance to the next iteration
	//as the iteration increases, we introduce more randomness into the model
	// (this is done via the getNonZero function)
	for(int iteration = 0; ; iteration += 10) {
		//calculate cost matrix
		for(int i = 0; i < points.size(); i++) {
			PathPoint *ipoint = points[i];
		
			if(ipoint->type == 0) numPickup++;
			else if(ipoint->type == 1) numDropoff++;
			else if(ipoint->type == 2) numDropped++;
			
			//from this point to itself
			costMatrix[i + 1][i] = getNonZero(0, iteration);
			
			//from this point to every other point
			for(int j = 0; j < points.size(); j++) {
				if(i != j)
					costMatrix[i + 1][j] = getNonZero(length(ipoint, points[j]), iteration);
			}
			
			//from the current location to this point
			costMatrix[0][i] = getNonZero(taxiPath->shortestPath(curr, ipoint->vert), iteration);
		}

	
		//calculate m matrix
		//first, we have to find earliest and latest
		
		//the current location must occur at time zero
		latest[0] = 0;
	
		for(int i = 0; i < points.size(); i++) {
			if(points[i]->type == 0 || points[i]->type == 2) {
				//this is a pickup or stand-alone dropoff point
				//the earliest time occurs when we go directly
				// from the current location to here
				//the latest time is set by the pickup constraint
				
				earliest[i] = costMatrix[0][i];
				latest[i + 1] = points[i]->remaining;
			} else if(points[i]->type == 1) {
				//this is a dropoff point
				//the earliest time occurs when we go directly
				// to the pickup point, then here
				//the latest time occurs when we get to the pickup
				// point the latest, and then here the latest
				// (stretch both pickup and service constraints)
				earliest[i] = costMatrix[0][pairIndex[i]] + costMatrix[pairIndex[i] + 1][i];
				latest[i + 1] = points[pairIndex[i]]->remaining + points[i]->remaining;
			}
		}
		
		//calculate m
		double test;
		for(int i = 0; i < points.size() + 1; i++) {
			for(int j = 0; j < points.size(); j++) {
				test = latest[i] + costMatrix[i][j] - earliest[j];
				if(test > 0) m[i][j] = test;
				else m[i][j] = 0;
			}
		}
		
		//find the number of binary columns
		//each x_ij determines whether or not the taxi will move
		// from i to j
		//in the comments below these movements will be referred
		// to as route segments (_from_ i _to_ j)
		int ncol = (points.size() + 1) * points.size();
		
		//find the total number of columns
		//besides the binary ones, there are ones for the time
		// at which the taxi will reach a point (B_i)
		int ncol_total = ncol + points.size() + 1;
		
		//create the lp instance
		lp = make_lp(0, ncol_total);
		
		//colno and row are used to define the constraints, and
		// later row will store the result from lpsolve
		//colno identifies the variable (column), and row identifies
		// the constants (multiplied by the variable); then, a
		// separate value determines the number of variables
		// that will be read (since we are using a sparse matrix -
		// otherwise we wouldn't need colno)
		//note**: column numbers are labeled starting from 1, not 0
		int *colno = new int[ncol_total];
		REAL *row = new REAL[ncol_total];
		
		//since we're going to be adding constraints equation
		// by equation, we set add row mode to make it faster
		set_add_rowmode(lp, TRUE);
		
		//disable most output from lpsolve
		set_verbose(lp, CRITICAL);
		
		//set timeout of three seconds so we don't spend forever on this model
		set_timeout(lp, 3);
		
		//set up the binary constraints
		for(int i = 0; i < ncol; i++) {
			set_binary(lp, i + 1, TRUE);
		}
		
		//constraints 1 to 3
		//these have one constraint per point
		for(int i = 0; i < points.size(); i++) {
			//1. the total number of route segments to here will
			// be equal to one
			for(int j = 0; j < points.size() + 1; j++) {
				colno[j] = j * points.size() + i + 1;
				row[j] = 1;
			}
			
			add_constraintex(lp, points.size() + 1, row, colno, EQ, 1);
			
			//2. there will be no route segment from here to itself
			colno[0] = (i + 1) * points.size() + i + 1;
			row[0] = 1;
			add_constraintex(lp, 1, row, colno, EQ, 0);
			
			//3. the total number of route segments from here will
			// be less than or equal to one (since the last point in
			// the route will be zero)
			for(int j = 0; j < points.size(); j++) {
				colno[j] = (i + 1) * points.size() + j + 1;
				row[j] = 1;
			}
			
			add_constraintex(lp, points.size(), row, colno, LE, 1);
		}
		
		//4. there will be exactly one route segment from the
		// current location
		for(int i = 0; i < points.size(); i++) {
			colno[i] = i + 1;
			row[i] = 1;
		}
	
		add_constraintex(lp, points.size(), row, colno, EQ, 1);
	
		//5. the relative time that the taxi reaches the current
		// location is zero
		colno[0] = ncol + 1;
		row[0] = 1;
		add_constraintex(lp, 1, row, colno, EQ, 0);
	
		//6. defined for each route segment (i, j)
		//if the segment (i, j) exists, then the time B_j
		// the taxi reaches j will be greater than
		//    B_i + time(i, j)
		// (time is interchangeable with distance)
		//in other words,
		//    B_j >= ( B_i + time(i, j) ) * x_ij
		//
		//**but that's non-linear (since B_i * x_ij)
		//to achieve the if statement, we subtract a large
		// number M from the right and M * x_ij on the left
		//the equation becomes:
		//    B_j - B_i - M*x_ij >= time(i, j) - M
		//
		//m_ij that we found earlier is suitable for M, since
		// if x_ij = 0 the equation reduces to
		//    B_j - B_i >= time(i, j) - M
		// >> M >= B_i + time(i, j) - B_j
		// we used the maximum possible value for B_i (latest[i])
		//  and the minimim for B_j (earliest[j]), so everything
		//  is good :)
		for(int i = 0; i < points.size() + 1; i++) {
			for(int j = 0; j < points.size(); j++) {
				colno[0] = ncol + 1 + i;
				colno[1] = ncol + 1 + j + 1; //make sure to add an extra 1 because we're not including current location
				colno[2] = i * points.size() + j + 1;
			
				double constant = costMatrix[i][j] - m[i][j];
			
				//only use positive constants or it seems to explode
				if(constant >= 0) {
					row[0] = -1;
					row[1] = 1;
					row[2] = -m[i][j];
		
					add_constraintex(lp, 3, row, colno, GE, constant);
				} else {
					row[0] = 1;
					row[1] = -1;
					row[2] = m[i][j];
		
					add_constraintex(lp, 3, row, colno, LE, -constant);
				}
			}
		}
	
		//constraints 7, 8, and 9
		for(int i = 0; i < points.size(); i++) {
			if(points[i]->type == 1) {
				//dropoff point
				
				//make sure to add an extra 1 because we're not including current location
				colno[0] = ncol + 1 + i + 1;
				colno[1] = ncol + 1 + pairIndex[i] + 1;
			
				row[0] = 1;
				row[1] = -1;
			
				//constraints on L_i (= B_i - B_pickup[i])
				
				//7. L_i >= time(pickup[i], i)
				add_constraintex(lp, 2, row, colno, GE, costMatrix[pairIndex[i] + 1][i]);
				
				//8. L_i <= remaining service constraint
				add_constraintex(lp, 2, row, colno, LE, points[i]->remaining);
			} else if(points[i]->type == 0 || points[i]->type == 2) {
				//pickup or stand-alone dropoff point
				colno[0] = ncol + 1 + i + 1;
				row[0] = 1;
				
				//9. B_i <= remaining pickup constraint
				add_constraintex(lp, 1, row, colno, LE, points[i]->remaining);
			}
		}
	
		//10. this used to enforce that all varibles be
		// non-negative, but it seems to be working now
		// (lpsolve makes variables non-negative unless
		// explicitly stated in a constraint)
		for(int i = ncol; i < ncol_total; i++) {
			colno[0] = i + 1;
			row[0] = 1;
			//add_constraintex(lp, 1, row, colno, GE, 0);
		}
		
		//disable rowmode because we're done building model
		set_add_rowmode(lp, FALSE);
		
		//objective function: minimize sum( time(i, j) * x_ij )
		//we maximize the negative though
		// (we could change to set_minim(lp), but it's the same thing)
		for(int i = 0; i < points.size() + 1; i++) {
			for(int j = 0; j < points.size(); j++) {
				colno[i * points.size() + j] = i * points.size() + j + 1;;
				row[i * points.size() + j] = -costMatrix[i][j];
			}
		}
	
		set_obj_fnex(lp, ncol, row, colno);
		set_maxim(lp); //maximize the objective function
		
		struct timeval solveStartTime;
		struct timeval solveEndTime;
		gettimeofday(&solveStartTime, NULL);
		
		int ret = solve(lp);
		
		gettimeofday(&solveEndTime, NULL);
		long tS = solveStartTime.tv_sec*1000000 + (solveStartTime.tv_usec);
		long tE = solveEndTime.tv_sec*1000000 + (solveEndTime.tv_usec);
		long solveTime = tE - tS;
		
		if(iteration == 0 && ret != TIMEOUT) {
			lpTotalTime += solveTime;
			if(solveTime > lpMaxTime) lpMaxTime = solveTime;
			lpNum++;
			
			cout << "lptimestatus: " << lpTotalTime / lpNum << " " << lpMaxTime << " " << lpNum << " " << solveTime << endl;
		}
		
		//if we didn't get the optimal solution, don't continue
		if(ret != OPTIMAL) {
			delete colno;
			delete row;
			delete_lp(lp);
			bestList.clear();
			
			if(ret == TIMEOUT) {
				//if we timed out, then we need to try again
				cout << "timed out on iteration " << iteration << ", advancing..." << endl;
				continue;
			} else {
				return bestList;
			}
		}
	
		get_variables(lp, row); //store variables in our row array
	
		//extract the ordering of the points from the x_ij in the row
		//at the same time, we calculate the route's distance
		
		int previous = 0;
		minTour = 0;
		
		for(int i = 0; i < points.size(); i++) {
			for(int j = 0; j < points.size(); j++) {
				if(row[previous * points.size() + j] == 1) {
					minTour += costMatrix[previous][j];
				
					bestList.push_back(points[j]);
					previous = j + 1;
					break;
				}
			}
		}

		delete colno;
		delete row;
		delete_lp(lp);
		
		//sometimes errors occur, probably because M was
		// too large and double-precision isn't accurate
		// enough
		//in these cases, since they're rare enough, we
		// assume that the model was infeasible
		if(bestList.size() != points.size()) {
			bestList.clear();
			minTour = numeric_limits<double>::max();
			return bestList;
		}
	
		return bestList;
	}
}
Ejemplo n.º 18
0
int main(int argc, char *argv[]) {

	int rv = -1;

	const char *device = NULL;
	const char *scriptname = NULL;

	// wait for socket if not there right away?
	int dowait = 0;

	terminal_init();


        int i=1;
        while(i<argc && argv[i][0]=='-' && argv[i][1] != 0) {
          	switch(argv[i][1]) {
            	case '?':
                	assert_single_char(argv[i]);
                	usage(EXIT_SUCCESS);    /* usage() exits already */
                	break;
            	case 'd':
                	assert_single_char(argv[i]);
                	if (i < argc-1) {
                  		i++;
                  		device = argv[i];
                  		log_info("main: device = %s\n", device);
                	} else {
                  		log_error("-d requires <device> parameter\n");
                  		exit(1);
                	}
                	break;
		case 'v':
			set_verbose();
			break;
		case 't':
			trace = 1;
			break;
		case 'w':
			dowait = 1;
			break;
            	default:
                	log_error("Unknown command line option %s\n", argv[i]);
                	usage(1);
                	break;
          	}
          	i++;
        }

	// next parameter is the script name
	if (i >= argc) {
		log_error("Script name parameter missing!\n");
		return -1;
	}

	scriptname = argv[i];
	i++;

	registry_t *script = load_script_from_file(scriptname);

	if (script != NULL) {

		int sockfd = socket_open(device, dowait);
	
		if (sockfd >= 0) {

			rv = execute_script(sockfd, script);
		}
	}

	
	return rv;
}
Ejemplo n.º 19
0
//Execute function
int LPSolveClass::Execute()
{
	/*
	std::cout << "---------------------------------\n";
	std::cout << "objective function\n";
	for (unsigned int i = 0; i < coefficients.size(); i++)
		std::cout << coefficients[i] << "\t";
	std::cout << "\nConstant Value = " << obj_const << std::endl;

	std::cout << "---------------------------------\n";
	std::cout << "Equality Constraints\n";	
	for (unsigned int i = 0; i < A_equ.size(); i++){
		//std::cout << "Row index = " << i << "\t\t";
		for (unsigned int j = 0; j < A_equ[i].size(); j++)
			std::cout << A_equ[i][j] << "\t";
		std::cout << "\n";
	}
	std::cout << "b\n";
	for (unsigned int i = 0; i < b_equ.size(); i++)
		std::cout << b_equ[i] << "\t";
	std::cout << "\n";


	std::cout << "---------------------------------\n";
	std::cout << "InEquality Constraints\n";	
	for (unsigned int i = 0; i < A_inequ.size(); i++){
		//std::cout << "Row index = " << i << "\t\t";
		for (unsigned int j = 0; j < A_inequ[i].size(); j++)
			std::cout << A_inequ[i][j] << "\t";
		std::cout << "\n";
	}
	std::cout << "b\n";
	for (unsigned int i = 0; i < b_inequ.size(); i++)
		std::cout << b_inequ[i] << "\t";
	std::cout << "\n";
	*/

	lprec *lp;
	int Ncol = coefficients.size(), *colno = NULL, j, ret = 0;
	REAL *row = NULL;
	
	/* We will build the model row by row
     So we start with creating a model with 0 rows and n columns */

	lp = make_lp(0, Ncol);
	if (lp == NULL)
		ret = 1;/* couldn't construct a new model... */
		
	if (ret == 0){
		//let us name our variables
		std::string s = "x";
		for (int i = 0; i < Ncol; i++){
			std::stringstream out;
			out << i;
			s = s + out.str();
			char *cpy = new char[s.size()+1] ;
			strcpy(cpy, s.c_str());			
			set_col_name(lp, i+1, cpy);
		}

		/* create space large enough for one row */
		colno = (int *) malloc(Ncol * sizeof(*colno));
    	row = (REAL *) malloc(Ncol * sizeof(*row));
		if ((colno == NULL) || (row == NULL))
      		ret = 2;
	}

	set_add_rowmode(lp, TRUE);
	//add the equation constraints
	if (ret == 0){
		/* makes building the model faster if it is done rows by row */
		if (A_equ.size() > 0){
			for (unsigned int i = 0; i < A_equ.size(); i++){//loop over the rows of equality constraints
				for (unsigned int j = 0; j < A_equ[i].size(); j++){//loop over the columns of equality constraints
					colno[j] = j+1;//add the j-th column to lpsolve
					row[j] = A_equ[i][j];
				}
				/* add the row to lpsolve */
				if(!add_constraintex(lp, A_equ[i].size(), row, colno, EQ, b_equ[i]))
					ret = 2;
			}
		}
	}
	
	//add the inequality constraints
	if (ret == 0){
		/* makes building the model faster if it is done rows by row */
		if (A_inequ.size() > 0){
			for (unsigned int i = 0; i < A_inequ.size(); i++){//loop over the rows of inequality constraints
				for (unsigned int j = 0; j < A_inequ[i].size(); j++){//loop over the columns of inequality constraints
					colno[j] = j+1;//add the j-th column to lpsolve
					row[j] = A_inequ[i][j];
				}
				/* add the row to lpsolve */
				if(!add_constraintex(lp, A_inequ[i].size(), row, colno, LE, b_inequ[i]))
					ret = 3;
			}
		}
	}

	//add the const constraint	
	if (ret == 0){
		if (b_const.size()>0){
			for (unsigned int i = 0; i < b_const.size(); i++){
				if (b_const[i] > 0){
					for (unsigned int j = 0; j < b_const.size(); j++){
						if (i == j){
							colno[j] = j+1;//add the j-th column to lpsolve
							row[j] = 1.0;						
						}				
						else{
							colno[j] = j+1;//add the j-th column to lpsolve
							row[j] = 0.0;
						}
					}
					if(!add_constraintex(lp, b_const.size(), row, colno, EQ, b_const[i]))
						ret = 4;		
				}
			}
		}
	}

	//set the variables to be integer
	if (ret == 0){
		for (int i = 0; i < Ncol; i++)
			set_int(lp, i+1, TRUE);
	}
	
	/* rowmode should be turned off again when done building the model */
	set_add_rowmode(lp, FALSE);	
	//add the objective function
	if (ret == 0){
		//set the objective function
		for (unsigned int i = 0; i < coefficients.size(); i++){
			colno[i] = i+1;
			row[i] = coefficients[i];
		}
		//set the objective in lpsolve
		if(!set_obj_fnex(lp, coefficients.size(), row, colno))
      		ret = 4;
	}

	//set the objective to minimize
	if (ret == 0){
		set_minim(lp);

		/* just out of curioucity, now show the model in lp format on screen */
    	/* this only works if this is a console application. If not, use write_lp and a filename */
    	write_LP(lp, stdout);

		/* I only want to see important messages on screen while solving */
    	set_verbose(lp, IMPORTANT);

    	/* Now let lpsolve calculate a solution */
    	ret = solve(lp);
    	if(ret == OPTIMAL)
      		ret = 0;
    	else
      		ret = 5;
	}

	//get some results
	if (ret == 0){
		/* a solution is calculated, now lets get some results */

    	/* objective value */
    	std::cout << "Objective value: " << get_objective(lp) << std::endl;

		/* variable values */
    	get_variables(lp, row);

		/* variable values */
		variables.resize(Ncol);
		for(j = 0; j < Ncol; j++)
			variables[j] = row[j];

		/* we are done now */
	}
	else{
		std::cout << "The optimal value can't be solved for linear programming, please check the constraints!!\n";
		exit(1);

	}
		
	
	std::cout << "print the result\t # of line segments is \n";
	for (int i = 0; i < Ncol; i++)
		std::cout << "index = " << i << "\t# = " << variables[i] << std::endl;

	/* free allocated memory */
  	if(row != NULL)
    	free(row);
  	if(colno != NULL)
    	free(colno);

	/* clean up such that all used memory by lpsolve is freed */
	if (lp != NULL)
		delete_lp(lp);

	return ret;
}
Ejemplo n.º 20
0
GaussSieve<ZT, F>::GaussSieve(ZZ_mat<ZT> &B, int alg_arg, bool ver, int seed)
{

  /* stats */
  b             = B;
  nr            = b.get_rows();
  nc            = b.get_cols();
  max_list_size = 0;
  iterations    = 0;
  collisions    = 0;
  reductions    = 0;
  samples       = 0;
  goal_sqr_norm = 0;
  mem_lower     = pow(2.0, 0.18 * nc);
  alg           = alg_arg;
  set_verbose(ver);

  /* sanity check */
  if (alg == 2)
  {
    if (verbose)
      cout << "# [info] running 2-sieve" << endl;
    mult            = 0.1;
    add             = 200.0;
    iterations_step = 200;
  }
  else if (alg == 3)
  {
    if (verbose)
      cout << "# [info] running 3-sieve" << endl;
    mult            = 0.1;
    add             = 100.0;
    iterations_step = 50;
  }
  else if (alg == 4)
  {
    if (verbose)
      cout << "# [info] running 4-sieve" << endl;
    mult            = 0.1;
    add             = 50.0;
    iterations_step = 5;
  }
  else
  {
    cout << " Error, only support 2-, 3- and 4-sieve" << endl;
    exit(1);
  }

  /* clean up list */
  free_list_queue();

  /* initialize sampler */
  Sampler = new KleinSampler<ZT, F>(b, verbose, seed);

  /* initialize list */
  init_list();

  /* further initialization by randomization */
  // init_list_rand();

  /* done initialization */
  max_list_size = List.size();

  /* output stats */
  if (verbose)
  {
    cout << "# [info] done initialization, size(List)=" << List.size() << endl;
    cout << "# [info] done initialization, size(Queue)=" << Queue.size() << endl;
    cout << "# [info] done initialization, mem_est=" << mem_lower << endl;
  }
}
Ejemplo n.º 21
0
int main(int argc, char **args) {
	int res = ERR_SUCCESS;

#ifdef WITH_PETSC
	PetscInitialize(&argc, &args, (char *) PETSC_NULL, PETSC_NULL);
#endif
	set_verbose(false);

	if (argc < 3) error("Not enough parameters");

	HcurlShapesetLobattoHex shapeset;

	printf("* Loading mesh '%s'\n", args[1]);
	Mesh mesh;
	Mesh3DReader mesh_loader;
	if (!mesh_loader.load(args[1], &mesh)) error("Loading mesh file '%s'\n", args[1]);

	printf("* Setting the space up\n");
	HcurlSpace space(&mesh, &shapeset);
	space.set_bc_types(bc_types);

	int o;
	sscanf(args[2], "%d", &o);
	order3_t order(o, o, o);
	printf("  - Setting uniform order to (%d, %d, %d)\n", o, o, o);
	space.set_uniform_order(order);

	int ndofs = space.assign_dofs();
	printf("  - Number of DOFs: %d\n", ndofs);

	printf("* Calculating a solution\n");

#if defined WITH_UMFPACK
	UMFPackMatrix mat;
	UMFPackVector rhs;
	UMFPackLinearSolver solver(&mat, &rhs);
#elif defined WITH_PARDISO
	PardisoMatrix mat;
	PardisoVector rhs;
	PardisoLinearSolver solver(&mat, &rhs);
#elif defined WITH_PETSC
	PetscMatrix mat;
	PetscVector rhs;
	PetscLinearSolver solver(&mat, &rhs);
#elif defined WITH_MUMPS
	MumpsMatrix mat;
	MumpsVector rhs;
	MumpsSolver solver(&mat, &rhs);
#endif

	WeakForm wf;
	wf.add_matrix_form(FORM_CB(bilinear_form), SYM);
	wf.add_vector_form(FORM_CB(linear_form));

	LinearProblem lp(&wf, &space);

	// assemble stiffness matrix
	Timer assemble_timer("Assembling stiffness matrix");
	assemble_timer.start();
	lp.assemble(&mat, &rhs);
	assemble_timer.stop();

	// solve the stiffness matrix
	Timer solve_timer("Solving stiffness matrix");
	solve_timer.start();
	bool solved = solver.solve();
	solve_timer.stop();

//	mat.dump(stdout, "a");
//	rhs.dump(stdout, "b");

	if (solved) {
		Solution sln(&mesh);
		sln.set_coeff_vector(&space, solver.get_solution());

		printf("* Solution:\n");
//		scalar *s = sln.get_solution_vector();
//		for (int i = 1; i <= ndofs; i++) {
//			printf(" x[% 3d] = " SCALAR_FMT "\n", i, SCALAR(s[i]));
//		}

		// output the measured values
		printf("%s: %s (%lf secs)\n", assemble_timer.get_name(), assemble_timer.get_human_time(), assemble_timer.get_seconds());
		printf("%s: %s (%lf secs)\n", solve_timer.get_name(), solve_timer.get_human_time(), solve_timer.get_seconds());

		ExactSolution ex_sln(&mesh, exact_solution);

		double hcurl_sln_norm = hcurl_norm(&sln);
		double hcurl_err_norm = hcurl_error(&sln, &ex_sln);
		printf(" - Hcurl solution norm:   % le\n", hcurl_sln_norm);
		printf(" - Hcurl error norm:      % le\n", hcurl_err_norm);

		double l2_sln_norm = l2_norm_hcurl(&sln);
		double l2_err_norm = l2_error_hcurl(&sln, &ex_sln);
		printf(" - L2 solution norm:      % le\n", l2_sln_norm);
		printf(" - L2 error norm:         % le\n", l2_err_norm);

		if (hcurl_err_norm > EPS || l2_err_norm > EPS) {
			// calculated solution is not enough precise
			res = ERR_FAILURE;
		}


#if defined OUTPUT_DIR
		// output
		printf("starting output\n");
		const char *of_name = OUTPUT_DIR "/solution.vtk";
		FILE *ofile = fopen(of_name, "w");
		if (ofile != NULL) {
			ExactSolution ex_sln(&mesh, exact_solution);
			DiffFilter eh(&sln, &ex_sln);
			DiffFilter eh_dx(&sln, &ex_sln, FN_DX, FN_DX);
//			DiffFilter eh_dy(mesh, &sln, &ex_sln, FN_DY, FN_DY);
//			DiffFilter eh_dz(mesh, &sln, &ex_sln, FN_DZ, FN_DZ);

//			GmshOutputEngine output(ofile);
			VtkOutputEngine output(ofile);
			output.out(&sln, "Uh", FN_VAL);
//			output.out(&sln, "Uh_0", FN_VAL_0);
//			output.out(&sln, "Uh_1", FN_VAL_1);
//			output.out(&sln, "Uh_2", FN_VAL_2);
//			output.vector_out(&sln, "Uh_dx", FN_DX);
//			output.vector_out(&sln, "Uh_dy", FN_DY);
//			output.vector_out(&sln, "Uh_dz", FN_DZ);
//			output.scalar_out(&sln, "Uh_dx_0", FN_DX_0);
//			output.scalar_out(&sln, "Uh_dx_1", FN_DX_1);
//			output.scalar_out(&sln, "Uh_dx_2", FN_DX_2);
//			output.out(&sln, "Uh dy", FN_DY_0);
//			output.out(&sln, "Uh dz", FN_DZ_0);

//			output.vector_out(&sln, "Uh_dx", FN_DX);
//			output.vector_out(&sln, "Uh_dy", FN_DY);
//			output.vector_out(&sln, "Uh_dz", FN_DZ);
//			output.scalar_out(&sln, "Uh_dx_0", FN_DX_0);
//			output.scalar_out(&sln, "Uh_dx_1", FN_DX_1);
//			output.scalar_out(&sln, "Uh_dx_2", FN_DX_2);
//			output.out(&sln, "Uh_dy", FN_DY_0);
//			output.out(&sln, "Uh_dz", FN_DZ_0);
//			output.out(&eh, "Eh", FN_VAL);
//			output.out(&eh_dx, "Eh_dx", FN_VAL);
//			output.out(&eh_dy, "Eh_dy");
//			output.out(&eh_dz, "Eh_dz");
//			output.out(&ex_sln, "U", FN_VAL);
//			output.out(&ex_sln, "U_dx", FN_DX);
//			output.out(&ex_sln, "U_dy", FN_DY);
//			output.out(&ex_sln, "U_dz", FN_DZ);
//			output.scalar_out(&ex_sln, "U_0", FN_VAL_0);
//			output.scalar_out(&ex_sln, "U_1", FN_VAL_1);
//			output.scalar_out(&ex_sln, "U_2", FN_VAL_2);
//			output.out(&ex_sln, "U_dy", FN_DY_0);
//			output.out(&ex_sln, "U_dz", FN_DZ_0);
			fclose(ofile);
		}
		else {
			warning("Can not open '%s' for writing.", of_name);
		}
#endif
	}

#ifdef WITH_PETSC
	mat.free();
	rhs.free();
	PetscFinalize();
#endif

	return res;
}
Ejemplo n.º 22
0
int main( const int argc, const char *argv[] )
  {
  int n = strlen( argv[0] );
  char loose = 0;
  const ap_Option options[] =
    {
    { 'G', "traditional",       ap_no  },
    { 'h', "help",              ap_no  },
    { 'l', "loose-exit-status", ap_no  },
    { 'p', "prompt",            ap_yes },
    { 's', "quiet",             ap_no  },
    { 's', "silent",            ap_no  },
    { 'v', "verbose",           ap_no  },
    { 'V', "version",           ap_no  },
    {   0, 0,                   ap_no } };
  Arg_parser parser;
  int argind;

  if( !ap_init( &parser, argc, argv, options, 0 ) )
    { show_error( "Memory exhausted", 0, 0 ); return 1; }
  if( ap_error( &parser ) )				/* bad option */
    { show_error( ap_error( &parser ), 0, 1 ); return 1; }
  invocation_name = argv[0];
  restricted_ = ( n > 2 && argv[0][n-3] == 'r' );

  for( argind = 0; argind < ap_arguments( &parser ); ++argind )
    {
    const int code = ap_code( &parser, argind );
    const char * arg = ap_argument( &parser, argind );
    if( !code ) break;					/* no more options */
    switch( code )
      {
      case 'G': traditional_ = 1; break;	/* backward compatibility */
      case 'h': show_help(); return 0;
      case 'l': loose = 1; break;
      case 'p': set_prompt( arg ); break;
      case 's': scripted_ = 1; break;
      case 'v': set_verbose(); break;
      case 'V': show_version(); return 0;
      default: show_error( "internal_error: uncaught option", 0, 0 ); return 3;
      }
    }
  setlocale( LC_ALL, "" );
  if( !init_buffers() ) return 1;

  while( argind < ap_arguments( &parser ) )
    {
    const char * arg = ap_argument( &parser, argind );
    if( !strcmp( arg, "-" ) ) { scripted_ = 1; ++argind; continue; }
    if( may_access_filename( arg ) )
      {
      if( read_file( arg, 0 ) < 0 && is_regular_file( 0 ) )
        return 2;
      else if( arg[0] != '!' ) set_def_filename( arg );
      }
    else
      {
      fputs( "?\n", stderr );
      if( arg[0] ) set_error_msg( "Invalid filename" );
      if( is_regular_file( 0 ) ) return 2;
      }
    break;
    }
  ap_free( &parser );

  return main_loop( loose );
  }
Ejemplo n.º 23
0
int main(int argc, char **args) {
	int res = ERR_SUCCESS;


#ifdef WITH_PETSC
	PetscInitialize(NULL, NULL, (char *) PETSC_NULL, PETSC_NULL);
#endif
	set_verbose(false);

	TRACE_START("trace.txt");
	DEBUG_OUTPUT_ON;
	SET_VERBOSE_LEVEL(0);

	try {
		for (int i = 0; i < 48; i++) {
			for (int j = 0; j < 48; j++) {
//		int i = 5; {
//		int j = 0; {
				printf("Config: %d, %d ", i, j);

				Mesh mesh;

				for (Word_t k = 0; k < countof(vtcs); k++)
					mesh.add_vertex(vtcs[k].x, vtcs[k].y, vtcs[k].z);
				Word_t h1[] = {
						hexs[0][i][0] + 1, hexs[0][i][1] + 1, hexs[0][i][2] + 1, hexs[0][i][3] + 1,
						hexs[0][i][4] + 1, hexs[0][i][5] + 1, hexs[0][i][6] + 1, hexs[0][i][7] + 1 };
				mesh.add_hex(h1);
				Word_t h2[] = {
						hexs[1][j][0] + 1, hexs[1][j][1] + 1, hexs[1][j][2] + 1, hexs[1][j][3] + 1,
						hexs[1][j][4] + 1, hexs[1][j][5] + 1, hexs[1][j][6] + 1, hexs[1][j][7] + 1 };
				mesh.add_hex(h2);
				// bc
				for (Word_t k = 0; k < countof(bnd); k++) {
					Word_t facet_idxs[Quad::NUM_VERTICES] = { bnd[k][0] + 1, bnd[k][1] + 1, bnd[k][2] + 1, bnd[k][3] + 1 };
					mesh.add_quad_boundary(facet_idxs, bnd[k][4]);
				}

				mesh.ugh();
//				mesh.dump();

//				Element *hx[] = { mesh.elements[1], mesh.elements[2] };
//				printf("[%d, %d]\n", hx[0]->get_face_orientation(1), hx[1]->get_face_orientation(2));

//				Word_t fidx[4];
//				hx[1]->get_face_vertices(2, fidx);
//				printf("FI: %d, %d, %d, %d\n", fidx[0], fidx[1], fidx[2], fidx[3]);
				printf("\n");

#ifdef OUTPUT_DIR
				BEGIN_BLOCK
					// output the mesh
					const char *of_name = OUTPUT_DIR "/ref.msh";
					FILE *ofile = fopen(of_name, "w");
					if (ofile != NULL) {
						GmshOutputEngine output(ofile);
						output.out(&mesh);
						fclose(ofile);
					}
					else {
						warning("Can not open '%s' for writing.", of_name);
					}
				END_BLOCK
#endif

				H1ShapesetLobattoHex shapeset;

//				printf("* Setting the space up\n");
				H1Space space(&mesh, &shapeset);
				space.set_bc_types(bc_types);
				space.set_essential_bc_values(essential_bc_values);

#ifdef XM_YN_ZO
				order3_t ord(4, 4, 4);
#elif defined XM_YN_ZO_2
				order3_t ord(4, 4, 4);
#elif defined X2_Y2_Z2
				order3_t ord(2, 2, 2);
#endif
//				printf("  - Setting uniform order to (%d, %d, %d)\n", dir_x, dir_y, dir_z);
				space.set_uniform_order(ord);

				space.assign_dofs();

//				printf("* Calculating a solution\n");

#if defined WITH_UMFPACK
				UMFPackMatrix mat;
				UMFPackVector rhs;
				UMFPackLinearSolver solver(&mat, &rhs);
#elif defined WITH_PARDISO
				PardisoLinearSolver solver;
#elif defined WITH_PETSC
				PetscMatrix mat;
				PetscVector rhs;
				PetscLinearSolver solver(&mat, &rhs);
#elif defined WITH_MUMPS
				MumpsMatrix mat;
				MumpsVector rhs;
				MumpsSolver solver(&mat, &rhs);
#endif

				WeakForm wf;
#ifdef DIRICHLET
				wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<ord_t, ord_t>, SYM);
				wf.add_vector_form(linear_form<double, scalar>, linear_form<ord_t, ord_t>);
#elif defined NEWTON
				wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<ord_t, ord_t>, SYM);
				wf.add_matrix_form_surf(bilinear_form_surf<double, scalar>, bilinear_form_surf<ord_t, ord_t>);
				wf.add_vector_form(linear_form<double, scalar>, linear_form<ord_t, ord_t>);
				wf.add_vector_form_surf(linear_form_surf<double, scalar>, linear_form_surf<ord_t, ord_t>);
#endif

				LinProblem lp(&wf);
				lp.set_space(&space);

				// assemble stiffness matrix
				lp.assemble(&mat, &rhs);

				// solve the stiffness matrix
				bool solved = solver.solve();
				if (!solved) throw ERR_FAILURE;

//				{
//					char file_name[1024];
//					sprintf(file_name, "%s/matrix-%d-%d", OUTPUT_DIR, i, j);
//					FILE *file = fopen(file_name, "w");
//					if (file != NULL) {
//						solver.dump_matrix(file, "A");
//						solver.dump_rhs(file, "b");
//
//						fclose(file);
//					}
//				}

				Solution sln(&mesh);
				sln.set_fe_solution(&space, solver.get_solution());

				ExactSolution exsln(&mesh, exact_solution);
				// norm
				double h1_sln_norm = h1_norm(&sln);
				double h1_err_norm = h1_error(&sln, &exsln);
				printf(" - H1 solution norm:   % le\n", h1_sln_norm);
				printf(" - H1 error norm:      % le\n", h1_err_norm);

				double l2_sln_norm = l2_norm(&sln);
				double l2_err_norm = l2_error(&sln, &exsln);
				printf(" - L2 solution norm:   % le\n", l2_sln_norm);
				printf(" - L2 error norm:      % le\n", l2_err_norm);

				assert(h1_sln_norm > 0 && h1_err_norm > 0);
				assert(l2_sln_norm > 0 && l2_err_norm > 0);

//				// out fn
//				char fname[4096];
//				sprintf(fname, "%s/cfg-%d-%d.pos", OUTPUT_DIR, i, j);
//				FILE *fnf = fopen(fname, "w");
//				assert(fnf != NULL);
//				GmshOutputEngine out(fnf);
//				char var[64];
//				sprintf(var, "%d_%d", i, j);
//				out.out(&sln, var);
//				fclose(fnf);
//
//				char mfname[4096];
//				sprintf(mfname, "%s/mesh-%d-%d.ref", OUTPUT_DIR, i, j);
//				FILE *mfnf = fopen(mfname, "w");
//				assert(mfnf != NULL);
//				GmshOutputEngine outm(mfnf);
//				outm.out(&mesh);
//				fclose(mfnf);

				if (h1_err_norm > EPS || l2_err_norm > EPS) {
					// calculated solution is not enough precise
					printf("Solution is not precise enough.\n");
					throw ERR_FAILURE;
				}

				printf("Passed\n");
			}
		}
	}
	catch (int e) {
		res = e;
		printf("Failed\n");
	}

#ifdef WITH_PETSC
	PetscFinalize();
#endif

	TRACE_END;

	return res;
}
Ejemplo n.º 24
0
int main(int argc, char **args) {
	int res = ERR_SUCCESS;

#ifdef WITH_PETSC
	PetscInitialize(&argc, &args, (char *) PETSC_NULL, PETSC_NULL);
#endif
	set_verbose(false);

	TRACE_START("trace.txt");
	DEBUG_OUTPUT_ON;
	SET_VERBOSE_LEVEL(0);

	if (argc < 5) error("Not enough parameters");

	sscanf(args[2], "%d", &m);
	sscanf(args[3], "%d", &n);
	sscanf(args[4], "%d", &o);

	printf("* Loading mesh '%s'\n", args[1]);
	Mesh mesh;
	Mesh3DReader mloader;
	if (!mloader.load(args[1], &mesh)) error("Loading mesh file '%s'\n", args[1]);

	H1ShapesetLobattoHex shapeset;
	printf("* Setting the space up\n");
	H1Space space(&mesh, &shapeset);
	space.set_bc_types(bc_types);

	int mx = maxn(4, m, n, o, 4);
	order3_t order(mx, mx, mx);
//	order3_t order(1, 1, 1);
//	order3_t order(m, n, o);
	printf("  - Setting uniform order to (%d, %d, %d)\n", mx, mx, mx);
	space.set_uniform_order(order);

	int ndofs = space.assign_dofs();
	printf("  - Number of DOFs: %d\n", ndofs);

	printf("* Calculating a solution\n");

#if defined WITH_UMFPACK
	UMFPackMatrix mat;
	UMFPackVector rhs;
	UMFPackLinearSolver solver(&mat, &rhs);
#elif defined WITH_PARDISO
	PardisoMatrix mat;
	PardisoVector rhs;
	PardisoLinearSolver solver(&mat, &rhs);
#elif defined WITH_PETSC
	PetscMatrix mat;
	PetscVector rhs;
	PetscLinearSolver solver(&mat, &rhs);
#elif defined WITH_MUMPS
	MumpsMatrix mat;
	MumpsVector rhs;
	MumpsSolver solver(&mat, &rhs);
#endif

	WeakForm wf;
	wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<ord_t, ord_t>, SYM);
	wf.add_vector_form(linear_form<double, scalar>, linear_form<ord_t, ord_t>);
	wf.add_vector_form_surf(linear_form_surf<double, scalar>, linear_form_surf<ord_t, ord_t>);

	LinearProblem lp(&wf, &space);

	// assemble stiffness matrix
	printf("  - assembling...\n"); fflush(stdout);
	Timer assemble_timer;
	assemble_timer.start();
	lp.assemble(&mat, &rhs);
	assemble_timer.stop();
	printf("%s (%lf secs)\n", assemble_timer.get_human_time(), assemble_timer.get_seconds());

	// solve the stiffness matrix
	printf("  - solving... "); fflush(stdout);
	Timer solve_timer;
	solve_timer.start();
	bool solved = solver.solve();
	solve_timer.stop();
	printf("%s (%lf secs)\n", solve_timer.get_human_time(), solve_timer.get_seconds());

//	mat.dump(stdout, "a");
//	rhs.dump(stdout, "b");

	if (solved) {
		Solution sln(&mesh);
		sln.set_coeff_vector(&space, solver.get_solution());

//		printf("* Solution:\n");
//		double *s = solver.get_solution();
//		for (int i = 1; i <= ndofs; i++) {
//			printf(" x[% 3d] = % lf\n", i, s[i]);
//		}

		ExactSolution ex_sln(&mesh, exact_solution);
		// norm
		double h1_sln_norm = h1_norm(&sln);
		double h1_err_norm = h1_error(&sln, &ex_sln);
		printf(" - H1 solution norm:   % le\n", h1_sln_norm);
		printf(" - H1 error norm:      % le\n", h1_err_norm);

		double l2_sln_norm = l2_norm(&sln);
		double l2_err_norm = l2_error(&sln, &ex_sln);
		printf(" - L2 solution norm:   % le\n", l2_sln_norm);
		printf(" - L2 error norm:      % le\n", l2_err_norm);

		if (h1_err_norm > EPS || l2_err_norm > EPS) {
			// calculated solution is not enough precise
			res = ERR_FAILURE;
		}

#if 0 //def OUTPUT_DIR
		printf("* Output\n");
		// output
		const char *of_name = OUTPUT_DIR "/solution.pos";
		FILE *ofile = fopen(of_name, "w");
		if (ofile != NULL) {
			ExactSolution ex_sln(&mesh, exact_solution);
			DiffFilter eh(&sln, &ex_sln);
//			DiffFilter eh_dx(&mesh, &sln, &ex_sln, FN_DX, FN_DX);
//			DiffFilter eh_dy(&mesh, &sln, &ex_sln, FN_DY, FN_DY);
//			DiffFilter eh_dz(&mesh, &sln, &ex_sln, FN_DZ, FN_DZ);

			GmshOutputEngine output(ofile);
			output.out(&sln, "Uh");
//			output.out(&sln, "Uh dx", FN_DX_0);
//			output.out(&sln, "Uh dy", FN_DY_0);
//			output.out(&sln, "Uh dz", FN_DZ_0);
			output.out(&eh, "Eh");
//			output.out(&eh_dx, "Eh dx");
//			output.out(&eh_dy, "Eh dy");
//			output.out(&eh_dz, "Eh dz");
			output.out(&ex_sln, "U");
//			output.out(&ex_sln, "U dx", FN_DX_0);
//			output.out(&ex_sln, "U dy", FN_DY_0);
//			output.out(&ex_sln, "U dz", FN_DZ_0);

			fclose(ofile);
		}
		else {
			warning("Can not open '%s' for writing.", of_name);
		}
#endif
	}
	else
		res = ERR_FAILURE;

#ifdef WITH_PETSC
	mat.free();
	rhs.free();
	PetscFinalize();
#endif

	TRACE_END;

	return res;
}
Ejemplo n.º 25
0
int main(int   argc,
	 char *argv[])
{
  if(setpgrp() < 0)
    perror("setpgrp()");

  if (parse_command_line(argc, argv) != 0)
    return 1;

#ifdef WIN32
  // if under windows, we need to define the locale directory
  bindtextdomain("poker2d", "./../locale");
#endif
  
  bind_textdomain_codeset("poker2d","UTF-8");    
  textdomain("poker2d");

  if (g_display)
  {
      char	tmp[64];
      snprintf(tmp, sizeof (tmp), "DISPLAY=%s", g_display);
      putenv(tmp);
  }
  
  if (g_gtk_rc_file)
  {
      char* file_name = strrchr(g_gtk_rc_file, '/')+1;

      int path_len = strlen(g_gtk_rc_file);
      int name_len = strlen(file_name);
      int newname_len = strlen(gettext(file_name));
      
      char* new_gtk_rc = malloc(sizeof(char)*(path_len-name_len+newname_len));
      memset(new_gtk_rc, 0, path_len-name_len+newname_len);
      memcpy(new_gtk_rc, g_gtk_rc_file, path_len-name_len);
      strcat(new_gtk_rc, gettext(file_name));
      
      char* tmp[2] = { new_gtk_rc, 0};
      gtk_rc_set_default_files(tmp);
      
      g_message("%s\n", new_gtk_rc);
      g_message(gettext("CANCEL"));
      
      g_free(g_gtk_rc_file);
      g_free(new_gtk_rc);
  }
  gtk_init (&argc, &argv);  

  set_verbose(g_want_verbose);

  if (!init_interface_io(g_hostname ? g_hostname : "127.0.0.1"))
    return 1;

  if (g_smiley_path)
    create_smiley_array(g_smiley_path, "smileys.xml");
  else
    create_smiley_array(".", "smileys.xml");
  gtk_main ();
  destroy_smiley_array();
  if (g_smiley_path) g_free(g_smiley_path);
  if (g_data_dir) g_free(g_data_dir);
  if (g_display) g_free(g_display);
  gui_set_glade_file(NULL);

  exit(0);
}