Esempio n. 1
0
void ProgEvaluateClass::run()
{
	MetaData MD((String)"classes@"+fnClass), MDclass;
	ClassEvaluation eval;
	if (verbose>0)
		init_progress_bar(MD.size());
	int idx=0;
	FOR_ALL_OBJECTS_IN_METADATA(MD)
	{
		int classNo;
		MD.getValue(MDL_REF,classNo,__iter.objId);
		MDclass.read(formatString("class%06d_images@%s",classNo,fnClass.c_str()));
		evaluateClass(MDclass,eval);
		MD.setValue(MDL_CLASSIFICATION_FRC_05,eval.FRC_05,__iter.objId);
		MD.setValue(MDL_CLASSIFICATION_DPR_05,eval.DPR_05,__iter.objId);
		idx++;
		if (verbose>0)
			progress_bar(idx);
	}
	if (verbose>0)
		progress_bar(MD.size());
	if (fnOut=="")
		fnOut=fnClass;
	MD.write((String)"classes@"+fnOut,MD_APPEND);
}
Esempio n. 2
0
void do_loading(void)
{
	do_wait("\nInitialising pipelines", 1);
	printf("%ssuccessful%s\n", COLOUR_GREEN, COLOUR_RESET);
	do_wait("Verifying target network", 3);
	printf("%ssuccessful%s\n", COLOUR_GREEN, COLOUR_RESET);
	do_wait("Discovering hardware cryptography acceleration", 3);
	printf("%ssuccessful%s\n", COLOUR_GREEN, COLOUR_RESET);
	do_wait("Probing target network", 2);
	printf("%ssuccessful%s\n", COLOUR_GREEN, COLOUR_RESET);
	do_wait("Initialising target network lockdown", 1);
	printf("%ssuccessful%s\n\n", COLOUR_GREEN, COLOUR_RESET);
	printf("%sObtaining internal authentication key...%s\n", COLOUR_YELLOW, COLOUR_RESET);
        charset = malloc(16);
	int i;
	for (i = 0; i < 10; i++) charset[i] = (i + 48);
	for (i = 10; i < 16; i++) charset[i] = (i + 55);
	do_password();
	free(charset);
	printf("%sLoading security grid access protocol...%s\n", COLOUR_YELLOW, COLOUR_RESET);
	progress_bar(5000, 10000);
	printf("%sLoading security grid access database...%s\n", COLOUR_YELLOW, COLOUR_RESET);
	progress_bar(1000, 7000);
	printf("%sPreparing core security framework...%s\n", COLOUR_YELLOW, COLOUR_RESET);
	progress_bar(5000, 25000);
	printf("%sInitialising core security framework...%s\n", COLOUR_YELLOW, COLOUR_RESET);
	progress_bar(2000, 50000);
	printf("%sInfiltrating target network...%s\n", COLOUR_YELLOW, COLOUR_RESET);
	progress_bar(100000, 300000);
}
void ParticleSorterMpi::run()
{

	int total_nr_images = MDin.numberOfObjects();
	features.resize(total_nr_images, NR_FEATURES);

	// Each node does part of the work
	long int my_first_image, my_last_image, my_nr_images;
	divide_equally(total_nr_images, node->size, node->rank, my_first_image, my_last_image);
	my_nr_images = my_last_image - my_first_image + 1;

	int barstep;
	if (verb > 0)
	{
		std::cout << "Calculating sorting features for all input particles..." << std::endl;
		init_progress_bar(my_nr_images);
		barstep = XMIPP_MAX(1, my_nr_images/ 60);
	}

	long int ipart = 0;
	FOR_ALL_OBJECTS_IN_METADATA_TABLE(MDin)
	{

		if (ipart >= my_first_image && ipart <= my_last_image)
		{
			if (verb > 0 && ipart % barstep == 0)
				progress_bar(ipart);

			calculateFeaturesOneParticle(ipart);

		}
		ipart++;
	}

	if (verb > 0)
		progress_bar(my_nr_images);

	// Combine results from all nodes
	MultidimArray<double> allnodes_features;
	allnodes_features.resize(features);
	MPI_Allreduce(MULTIDIM_ARRAY(features), MULTIDIM_ARRAY(allnodes_features), MULTIDIM_SIZE(features), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
	features = allnodes_features;

	// Only the master writes out files
	if (verb > 0)
	{
		normaliseFeatures();

		writeFeatures();
	}

}
Esempio n. 4
0
MateAppProgressKey
mate_app_progress_manual (MateApp * app,
			   const gchar * description,
			   MateAppProgressCancelFunc cancel_cb,
			   gpointer data)
{
  ProgressKeyReal * key;

  g_return_val_if_fail (app != NULL, NULL);
  g_return_val_if_fail (MATE_IS_APP(app), NULL);
  g_return_val_if_fail (description != NULL, NULL);

  key = g_new (ProgressKeyReal, 1);

  key->app = app;
  key->cancel_cb = cancel_cb;
  key->data = data;
  key->timeout_tag = INVALID_TIMEOUT;

  if ( mate_app_has_appbar_progress(app) &&
  /* FIXME !!! */
       0 /*mate_preferences_get_statusbar_dialog() */) {
    progress_bar    (description, key);
  }
  else {
    progress_dialog (description, key);
  }

  /* Make sure progress stops if the app is destroyed. */
  key->handler_id = g_signal_connect(app, "destroy",
				     G_CALLBACK(stop_progress_cb),
				     key);

  return key;
}
Esempio n. 5
0
int sha1_update_done_cb(void *p) {
    val++;
    UNUSED(p);
    progress_bar();

    return 0;
}
    void TestBarCleansFilesUpAfterException()
    {
        double smidge = 1e-8;

        {
            ProgressReporter progress_bar("ProgressReporterException", 1.0, 10.0);
            try
            {
                progress_bar.PrintInitialising();
                for (unsigned i=0; i<=900; i++)
                {
                    double t = 1.0 + ((i+0.0)/1000)*9.0 - smidge;
                    progress_bar.Update(t);
                }
                EXCEPTION("Throw");
            }
            catch(Exception&)
            {
            }
        }

        // File should now be closed since  progress_bar is out of scope
        std::string results_dir = OutputFileHandler::GetChasteTestOutputDirectory() + "ProgressReporterException/";
        FileComparison(results_dir + "progress_status.txt", "global/test/data/bad_progress_status.txt").CompareFiles();
    }
void torrent_view::print_torrent(lt::torrent_status const& s, bool selected)
{
	int pos = 0;
	char str[512];

	// the active torrent is highligted in the list
	// this inverses the forground and background colors
	char const* selection = "";
	if (selected)
		selection = "\x1b[1m\x1b[44m";

	char queue_pos[16] = {0};
	if (s.queue_position == -1)
		snprintf(queue_pos, sizeof(queue_pos), "-");
	else
		snprintf(queue_pos, sizeof(queue_pos), "%d", s.queue_position);

	std::string name = s.name;
	if (name.size() > 50) name.resize(50);

	color_code progress_bar_color = col_yellow;
	if (!s.error.empty()) progress_bar_color = col_red;
	else if (s.paused) progress_bar_color = col_blue;
	else if (s.state == lt::torrent_status::downloading_metadata)
		progress_bar_color = col_magenta;
	else if (s.current_tracker.empty())
		progress_bar_color = col_green;

	pos += snprintf(str + pos, sizeof(str) - pos, "%s%c%-3s %-50s %s%s %s (%s) "
		"%s (%s) %5d:%-5d %s %s %c%s"
		, selection
		, s.is_loaded ? 'L' : ' '
		, queue_pos
		, name.c_str()
		, progress_bar(s.progress_ppm / 1000, 35, progress_bar_color, '-', '#', torrent_state(s)).c_str()
		, selection
		, color(add_suffix(s.download_rate, "/s"), col_green).c_str()
		, color(add_suffix(s.total_download), col_green).c_str()
		, color(add_suffix(s.upload_rate, "/s"), col_red).c_str()
		, color(add_suffix(s.total_upload), col_red).c_str()
		, s.num_peers - s.num_seeds, s.num_seeds
		, color(add_suffix(s.all_time_download), col_green).c_str()
		, color(add_suffix(s.all_time_upload), col_red).c_str()
		, s.need_save_resume?'S':' ', esc("0"));

	// if this is the selected torrent, restore the background color
	if (selected)
		pos += snprintf(str + pos, sizeof(str) - pos, "%s", esc("0"));

	pos += snprintf(str + pos, sizeof(str) - pos, "\x1b[K");

	if (m_width + 1 < sizeof(str))
		str[m_width + 1] = '\0';

	print(str);
}
Esempio n. 8
0
void disable_progress_bar()
{
	pthread_mutex_lock(&progress_mutex);
	if(progress_enabled)  {
		progress_bar(cur_uncompressed, estimated_uncompressed, columns);
		printf("\n");
	}
	progress_enabled = 0;
	pthread_mutex_unlock(&progress_mutex);
}
Esempio n. 9
0
void ParticlePolisherMpi::polishParticlesAllMicrographs()
{

	if (!do_start_all_over && exists(fn_out + ".star"))
	{
		if (verb > 0)
			std::cout << std::endl << " + " << fn_out << ".star already exists: skipping polishing of the particles." << std::endl;
		return;
	}

	int total_nr_micrographs = exp_model.average_micrographs.size();

	// Each node does part of the work
	long int my_first_micrograph, my_last_micrograph, my_nr_micrographs;
	divide_equally(total_nr_micrographs, node->size, node->rank, my_first_micrograph, my_last_micrograph);
	my_nr_micrographs = my_last_micrograph - my_first_micrograph + 1;

	// Loop over all average micrographs
	int barstep;
	if (verb > 0)
	{
		std::cout << " + Write out polished particles for all micrographs ... " << std::endl;
		init_progress_bar(my_nr_micrographs);
		barstep = XMIPP_MAX(1, my_nr_micrographs/ 60);
	}

    for (long int i = my_first_micrograph; i <= my_last_micrograph; i++)
	{
    	if (verb > 0 && i % barstep == 0)
			progress_bar(i);

    	polishParticlesOneMicrograph(i);
	}

   	if (verb > 0)
   		progress_bar(my_nr_micrographs);

    if (node->isMaster())
    	writeStarFilePolishedParticles();

    MPI_Barrier(MPI_COMM_WORLD);

}
// Outliers ===============================================================
void ProgClassifyCL2DCore::computeCores()
{
    if (verbose && node->rank==0)
        std::cerr << "Computing cores ...\n";
    ProgAnalyzeCluster analyzeCluster;
    analyzeCluster.verbose=0;
    analyzeCluster.NPCA=NPCA;
    analyzeCluster.Niter=10;
    analyzeCluster.distThreshold=thPCAZscore;
    analyzeCluster.dontMask=false;

    MetaData MD;
    size_t first, last;
    size_t Nblocks=blocks.size();
    if (verbose && node->rank==0)
        init_progress_bar(Nblocks);
    while (taskDistributor->getTasks(first, last))
        for (size_t idx=first; idx<=last; ++idx)
        {
            // Remove outliers in the PCA projection
            analyzeCluster.SFin.clear();
            analyzeCluster.fnSel=blocks[idx].block+"@"+blocks[idx].fnLevel;
            analyzeCluster.fnOut=blocks[idx].fnLevel.insertBeforeExtension((String)"_core_"+blocks[idx].block);
            analyzeCluster.run();

            // Remove outliers from file
            MD.read(analyzeCluster.fnOut);
            MD.removeDisabled();
            MD.write(analyzeCluster.fnOut,MD_APPEND);

            if (verbose && node->rank==0)
                progress_bar(idx);
        }
    taskDistributor->wait();
    if (verbose && node->rank==0)
        progress_bar(Nblocks);

    // Gather all results
    gatherResults(0,"core");
}
Esempio n. 11
0
void LLWidgetReg::initClass(bool register_widgets)
{
	// Only need to register if the Windows linker has optimized away the
	// references to the object files.
	if (register_widgets)
	{
		LLDefaultChildRegistry::Register<LLButton> button("button");
		LLDefaultChildRegistry::Register<LLMenuButton> menu_button("menu_button");
		LLDefaultChildRegistry::Register<LLCheckBoxCtrl> check_box("check_box");
		LLDefaultChildRegistry::Register<LLComboBox> combo_box("combo_box");
		LLDefaultChildRegistry::Register<LLFilterEditor> filter_editor("filter_editor");
		LLDefaultChildRegistry::Register<LLFlyoutButton> flyout_button("flyout_button");
		LLDefaultChildRegistry::Register<LLContainerView> container_view("container_view");
		LLDefaultChildRegistry::Register<LLIconCtrl> icon("icon");
		LLDefaultChildRegistry::Register<LLLoadingIndicator> loading_indicator("loading_indicator");
		LLDefaultChildRegistry::Register<LLLineEditor> line_editor("line_editor");
		LLDefaultChildRegistry::Register<LLMenuItemSeparatorGL> menu_item_separator("menu_item_separator");
		LLDefaultChildRegistry::Register<LLMenuItemCallGL> menu_item_call_gl("menu_item_call");
		LLDefaultChildRegistry::Register<LLMenuItemCheckGL> menu_item_check_gl("menu_item_check");
		LLDefaultChildRegistry::Register<LLMenuGL> menu("menu");
		LLDefaultChildRegistry::Register<LLMenuBarGL> menu_bar("menu_bar");
		LLDefaultChildRegistry::Register<LLContextMenu> context_menu("context_menu");
		LLDefaultChildRegistry::Register<LLMultiSlider> multi_slider_bar("multi_slider_bar");
		LLDefaultChildRegistry::Register<LLMultiSliderCtrl> multi_slider("multi_slider");
		LLDefaultChildRegistry::Register<LLPanel> panel("panel", &LLPanel::fromXML);
		LLDefaultChildRegistry::Register<LLLayoutStack> layout_stack("layout_stack");
		LLDefaultChildRegistry::Register<LLProgressBar> progress_bar("progress_bar");
		LLDefaultChildRegistry::Register<LLRadioGroup> radio_group("radio_group");
		LLDefaultChildRegistry::Register<LLSearchEditor> search_editor("search_editor");
		LLDefaultChildRegistry::Register<LLScrollContainer> scroll_container("scroll_container");
		LLDefaultChildRegistry::Register<LLScrollingPanelList> scrolling_panel_list("scrolling_panel_list");
		LLDefaultChildRegistry::Register<LLScrollListCtrl> scroll_list("scroll_list");
		LLDefaultChildRegistry::Register<LLSlider> slider_bar("slider_bar");
		LLDefaultChildRegistry::Register<LLSliderCtrl> slider("slider");
		LLDefaultChildRegistry::Register<LLSpinCtrl> spinner("spinner");
		LLDefaultChildRegistry::Register<LLStatBar> stat_bar("stat_bar");
		//LLDefaultChildRegistry::Register<LLPlaceHolderPanel> placeholder("placeholder");
		LLDefaultChildRegistry::Register<LLTabContainer> tab_container("tab_container");
		LLDefaultChildRegistry::Register<LLTextBox> text("text");
		LLDefaultChildRegistry::Register<LLTimeCtrl> time("time");
		LLDefaultChildRegistry::Register<LLTextEditor> simple_text_editor("simple_text_editor");
		LLDefaultChildRegistry::Register<LLUICtrl> ui_ctrl("ui_ctrl");
		LLDefaultChildRegistry::Register<LLStatView> stat_view("stat_view");
		//LLDefaultChildRegistry::Register<LLUICtrlLocate> locate("locate");
		//LLDefaultChildRegistry::Register<LLUICtrlLocate> pad("pad");
		LLDefaultChildRegistry::Register<LLViewBorder> view_border("view_border");
	}

	// *HACK: Usually this is registered as a viewer text editor
	LLDefaultChildRegistry::Register<LLTextEditor> text_editor("text_editor");
}
Esempio n. 12
0
int main(int argc,char *argv[]) 
{
	Fl_Socket socket;
	sock = &socket;

    Fl_Window main_window(600,400,"Socket test");

	Fl_Group top_group(0,0,200,25);
	top_group.layout_align(FL_ALIGN_TOP);

	Fl_Box progress_text(0,0,150,25);
	p_text = &progress_text;

	Fl_ProgressBar progress_bar(150,0,50,25);
	p_bar = &progress_bar;

	top_group.resizable(p_bar);
	top_group.store_sizes();
	top_group.end();

	Fl_Text_Buffer buf;
    Fl_Text_Editor	editor(10,10,200,100);

    editor.layout_align(FL_ALIGN_CLIENT);
    editor.buffer(buf);

	textbuf = &buf;
	textdisp = &editor;

    Fl_Group status_line(0,0,200,25);
    status_line.layout_align(FL_ALIGN_BOTTOM);

    Fl_Input url_input(50, 0, 100, 25, "http://");
	url_input.value("www.fltk.org/index.php");

    Fl_Button go_button(150, 0, 50, 25, "Go!");
    go_button.callback(go_callback);
    
	status_line.resizable(url_input);
	status_line.store_sizes();
	status_line.end();

    input = &url_input;

    main_window.end();
    main_window.resizable(main_window);
    main_window.show(argc,argv);

    return Fl::run();
}
Esempio n. 13
0
int sendfile(int sockfd,int fd)
{
	char buf[LEN];
    int nread,count=0;
    int size=file_size_fd(fd);

	while((nread=Read(fd,buf,sizeof(buf)))>0)
	{
		Writen(sockfd,buf,nread);
        count+=nread;
        progress_bar((count/size)*100);
	}

	return 0;
}
Esempio n. 14
0
void Sudoku::process(std::istream& input, std::ostream& output) {
  std::vector<std::string> lines;
  std::copy(std::istream_iterator<std::string>(input),
            std::istream_iterator<std::string>(),
            std::back_inserter(lines));
  int count = 0;
  int total = lines.size();
  for (auto& line: lines) {
    Sudoku sudoku(line);
    sudoku.solve();
    output << sudoku;
    count++;
    progress_bar(count, total);
  }
  std::cout << std::endl;
}
Esempio n. 15
0
/* start progress bar animation if choice 1
   or start throwing stick animation if choice 2 */
static void animate(const int type, const int len)
{
	if (type == 1) {
		progress_bar(len);
	} else if (type == 2) {
		/* loop to run throwing stick animation forwards and backwards */
		int i=0;
		for (;;) {
			throwing_stick(len, (i % 2) ? 'b' : 'f', 1);
			i = (i+1) % 2;
		}
	} else {
		fprintf(stderr, "choice must be 1 (progress bar) or 2 (throwing stick)\n");
		exit(EXIT_FAILURE);
	}
}
Esempio n. 16
0
void run()
{
	long t, export=1;
	
	FILE *f_hi, *f_st;
	
	f_hi = fopen("hi.dat","w");	
	
	for (t=0; t<num_of_iteration; t++){
		export_conf(t,export);
		write_hi(f_hi,t);
		progress_bar(t);
        //printf("prova_run\n");
		one_step();
	}

	fclose(f_hi);
}
  static bool genmatrix(const char *filename,
                        const ContextID &cid,
                        DecoderFeatureIndex *fi,
                        int factor,
                        int default_cost) {
    std::ofstream ofs(filename);
    CHECK_DIE(ofs) << "permission denied: " << filename;

    LearnerPath path;
    LearnerNode rnode;
    LearnerNode lnode;
    rnode.stat = lnode.stat = MECAB_NOR_NODE;
    rnode.rpath = &path;
    lnode.lpath = &path;
    path.lnode = &lnode;
    path.rnode = &rnode;

    const std::map<std::string, int> &left =  cid.left_ids();
    const std::map<std::string, int> &right = cid.right_ids();

    CHECK_DIE(left.size())  << "left id size is empty";
    CHECK_DIE(right.size()) << "right id size is empty";

    ofs << right.size() << ' ' << left.size() << std::endl;

    size_t l = 0;
    for (std::map<std::string, int>::const_iterator rit = right.begin();
         rit != right.end();
         ++rit) {
      ++l;
      progress_bar("emitting matrix      ", l+1, right.size());
      for (std::map<std::string, int>::const_iterator lit = left.begin();
           lit != left.end();
           ++lit) {
        path.rnode->wcost = 0;
        fi->buildBigramFeature(&path, rit->first.c_str(), lit->first.c_str());
        fi->calcCost(&path);
        ofs << rit->second << ' ' << lit->second << ' '
            << tocost(path.cost, factor, default_cost) << std::endl;
      }
    }

    return true;
  }
    void TestBar()
    {
        // This is in a block to make sure the file gets closed (i.e. destructor called)
        {
            ProgressReporter progress_bar("ProgressReporter", 1.0, 10.0);

            progress_bar.PrintInitialising();
            for (unsigned i=0; i<=1000; i++)
            {
                double t = 1.0 + ((i+0.0)/1000)*9.0;
                progress_bar.Update(t);
            }

            progress_bar.PrintFinalising();
        }

        std::string results_dir = OutputFileHandler::GetChasteTestOutputDirectory() + "ProgressReporter/";
        FileComparison(results_dir + "progress_status.txt", "global/test/data/good_progress_status.txt").CompareFiles();

    }
Esempio n. 19
0
void
pass1b(void)
{
	int c, i;
	union dinode *dp;
	struct inodesc idesc;
	ino_t inumber;

	memset(&idesc, 0, sizeof(struct inodesc));
	idesc.id_type = ADDR;
	idesc.id_func = pass1bcheck;
	duphead = duplist;
	inumber = 0;
	for (c = 0; c < sblock->fs_ncg; c++) {
		if (got_siginfo) {
			fprintf(stderr,
			    "%s: phase 1b: cyl group %d of %d (%d%%)\n",
			    cdevname(), c, sblock->fs_ncg,
			    c * 100 / sblock->fs_ncg);
			got_siginfo = 0;
		}
#ifdef PROGRESS
		progress_bar(cdevname(), "phase 1b", c, sblock->fs_ncg);
#endif /* PROGRESS */
		for (i = 0; i < sblock->fs_ipg; i++, inumber++) {
			if (inumber < ROOTINO)
				continue;
			dp = ginode(inumber);
			if (dp == NULL)
				continue;
			idesc.id_number = inumber;
			if (inoinfo(inumber)->ino_state != USTATE &&
			    (ckinode(dp, &idesc) & STOP))
				return;
		}
	}
#ifdef PROGRESS
	progress_done();
#endif /* PROGRESS */
}
Esempio n. 20
0
void *progress_thrd(void *arg)
{
	struct timespec requested_time, remaining;
	struct itimerval itimerval;
	struct winsize winsize;

	if(ioctl(1, TIOCGWINSZ, &winsize) == -1) {
		if(isatty(STDOUT_FILENO))
			printf("TIOCGWINSZ ioctl failed, defaulting to 80 "
				"columns\n");
		columns = 80;
	} else
		columns = winsize.ws_col;
	signal(SIGWINCH, sigwinch_handler);
	signal(SIGALRM, sigalrm_handler);

	itimerval.it_value.tv_sec = 0;
	itimerval.it_value.tv_usec = 250000;
	itimerval.it_interval.tv_sec = 0;
	itimerval.it_interval.tv_usec = 250000;
	setitimer(ITIMER_REAL, &itimerval, NULL);

	requested_time.tv_sec = 0;
	requested_time.tv_nsec = 250000000;

	while(1) {
		int res = nanosleep(&requested_time, &remaining);

		if(res == -1 && errno != EINTR)
			BAD_ERROR("nanosleep failed in progress thread\n");

		if(progress_enabled) {
			pthread_mutex_lock(&progress_mutex);
			progress_bar(cur_uncompressed, estimated_uncompressed,
				columns);
			pthread_mutex_unlock(&progress_mutex);
		}
	}
}
Esempio n. 21
0
    int create_cache_db_impl()
    {
        // Adding 0% mark at the very beginning of the program
        KApp::CProgressBar progress_bar(1);
        progress_bar.Process ( 0, true );

        VDBObjects::CVDBManager mgr;
        mgr.Make();

        VDBObjects::CVDatabase vdb = mgr.OpenDB (g_Params.dbPathSrc);

        // Scan SEQUENCE table to find mate_alignment_ids that have to be cached
        KLib::CKVector vect;
        size_t count = FillKVectorWithAlignIDs ( vdb, g_Params.cursor_cache_size, vect );

        if ( count*2 >= g_Params.min_cache_count )
        {
            // For each id in vect cache the PRIMARY_ALIGNMENT record
            CachePrimaryAlignment ( mgr, vdb, g_Params.cursor_cache_size, vect, count*2, progress_bar );
        }
        else
        {
            if ( ::Quitting() == 0 )
            {
                PLOGMSG ( klogWarn,
                    ( klogWarn, 
                    "The cache db will not be created because there is not "
                    "enough records to cache: $(COUNT) is found and minimum $(MIN_COUNT) is required. "
                    "The minimum required number can be changed via $(OPTION_MIN_CACHE_COUNT) parameter.",
                    "COUNT=%zu,MIN_COUNT=%zu,OPTION_MIN_CACHE_COUNT=%s",
                    count*2, g_Params.min_cache_count, OPTION_MIN_CACHE_COUNT
                    ));
            }
        }

        mgr.Release (); // should not be necessary - destructor should do job
        return 0;
    }
Esempio n. 22
0
void ProgXrayImport::run()
{
    // Delete output stack if it exists
    fnOut = fnRoot + ".mrc";
    fnOut.deleteFile();

    /* Turn off error handling */
    H5Eset_auto(H5E_DEFAULT, NULL, NULL);

    if (dSource == MISTRAL)
        H5File.openFile(fnInput, H5F_ACC_RDONLY);


    // Reading bad pixels mask
    if ( !fnBPMask.empty() )
    {
        std::cerr << "Reading bad pixels mask from "+fnBPMask << "." << std::endl;
        bpMask.read(fnBPMask);
        if ( (cropSizeX + cropSizeY ) > 0 )
            bpMask().selfWindow(cropSizeY,cropSizeX,
                                (int)(YSIZE(bpMask())-cropSizeY-1),(int)(XSIZE(bpMask())-cropSizeX-1));
        STARTINGX(bpMask()) = STARTINGY(bpMask()) = 0;
    }


    // Setting the image projections list
    switch (dSource)
    {
    case MISTRAL:
        {
            inMD.read(fnInput);
            H5File.getDataset("NXtomo/data/rotation_angle", anglesArray, false);
            H5File.getDataset("NXtomo/instrument/sample/ExpTimes", expTimeArray, false);
            H5File.getDataset("NXtomo/instrument/sample/current", cBeamArray);

            /* In case there is no angles information we set them to to an increasing sequence
             * just to be able to continue importing data */
            if ( anglesArray.size() != inMD.size() )
            {
                reportWarning("Input file does not contains angle information. Default sequence used.");
                anglesArray.resizeNoCopy(inMD.size());
                anglesArray.enumerate();
            }

            // If expTime is empty or only one single value in nexus file then we fill with 1
            if (expTimeArray.size() < 2)
            {
                reportWarning("Input file does not contains tomogram exposition time information.");
                expTimeArray.initConstant(anglesArray.size(), 1.);
            }
            // If current is empty or only one single value in nexus file then we fill with 1
            if (cBeamArray.size() < 2)
            {
                reportWarning("Input file does not contains tomogram current beam information.");
                cBeamArray.initConstant(anglesArray.size(), 1.);
            }
            // Since Alba does not provide slit width, we set to ones
            slitWidthArray.initConstant(anglesArray.size(), 1.);
        }
        break;
    case BESSY:
        {
            size_t objId;

            for (size_t i = tIni; i <= tEnd; ++i)
            {
                objId = inMD.addObject();
                inMD.setValue(MDL_IMAGE, fnInput + formatString("/img%d.spe", i), objId);
            }
            break;
        }
    case GENERIC:
        {
            // Get Darkfield
            std::cerr << "Getting darkfield from "+fnInput << " ..." << std::endl;
            getDarkfield(fnInput, IavgDark);
            if (XSIZE(IavgDark())!=0)
                IavgDark.write(fnRoot+"_darkfield.xmp");


            std::vector<FileName> listDir;
            fnInput.getFiles(listDir);
            size_t objId;

            for (size_t i = 0; i < listDir.size(); ++i)
            {
                if (!listDir[i].hasImageExtension())
                    continue;
                objId = inMD.addObject();
                inMD.setValue(MDL_IMAGE, fnInput+"/"+listDir[i], objId);
            }
        }
        break;
    }

    inMD.findObjects(objIds);
    size_t nIm = inMD.size();

    // Create empty output stack file

    getImageInfo(inMD, imgInfo);


    /* Get the flatfield:: We get the FF after the image list because we need the image size to adapt the FF
     * in case they were already cropped.
     */
    if (!fnFlat.empty())
    {
        std::cout << "Getting flatfield from "+fnFlat << " ..." << std::endl;
        getFlatfield(fnFlat,IavgFlat);
        if ( XSIZE(IavgFlat()) != 0 )
        {
            FileName ffName = fnRoot+"_flatfield_avg.xmp";
            IavgFlat.write(ffName);
            fMD.setValue(MDL_IMAGE, ffName, fMD.addObject());
        }
    }

    createEmptyFile(fnOut, imgInfo.adim.xdim-cropSizeXi-cropSizeXe, imgInfo.adim.ydim-cropSizeYi-cropSizeYe, 1, nIm);

    // Process images
    td = new ThreadTaskDistributor(nIm, XMIPP_MAX(1, nIm/30));
    tm = new ThreadManager(thrNum, this);
    std::cerr << "Getting data from " << fnInput << " ...\n";
    init_progress_bar(nIm);
    tm->run(runThread);
    progress_bar(nIm);

    // Write Metadata and angles
    MetaData MDSorted;
    MDSorted.sort(outMD,MDL_ANGLE_TILT);
    MDSorted.write("tomo@"+fnRoot + ".xmd");
    if ( fMD.size() > 0 )
        fMD.write("flatfield@"+fnRoot + ".xmd", MD_APPEND);

    // We also reference initial and final images at 0 degrees for Mistral tomograms
    if ( dSource == MISTRAL )
    {
        fMD.clear();
        FileName degree0Fn = "NXtomo/instrument/sample/0_degrees_initial_image";
        if ( H5File.checkDataset(degree0Fn.c_str()))
            fMD.setValue(MDL_IMAGE, degree0Fn + "@" + fnInput, fMD.addObject());
        degree0Fn = "NXtomo/instrument/sample/0_degrees_final_image";
        if ( H5File.checkDataset(degree0Fn.c_str()))
            fMD.setValue(MDL_IMAGE, degree0Fn + "@" + fnInput, fMD.addObject());
        if ( fMD.size() > 0 )
            fMD.write("degree0@"+fnRoot + ".xmd", MD_APPEND);
    }

    // Write tlt file for IMOD
    std::ofstream fhTlt;
    fhTlt.open((fnRoot+".tlt").c_str());
    if (!fhTlt)
        REPORT_ERROR(ERR_IO_NOWRITE,fnRoot+".tlt");
    FOR_ALL_OBJECTS_IN_METADATA(MDSorted)
    {
        double tilt;
        MDSorted.getValue(MDL_ANGLE_TILT,tilt,__iter.objId);
        fhTlt << tilt << std::endl;
    }
    fhTlt.close();
    delete td;
    delete tm;
}
void ProgAngularProjectLibrary::project_angle_vector (int my_init, int my_end, bool verbose)
{
    Projection P;
    FileName fn_proj;
    double rot,tilt,psi;
    int mySize;
    int numberStepsPsi = 1;

    mySize=my_end-my_init+1;
    if (psi_sampling < 360)
    {
        numberStepsPsi = (int) (359.99999/psi_sampling);
        mySize *= numberStepsPsi;
    }

    if (verbose)
        init_progress_bar(mySize);
    int myCounter=0;


    for (double mypsi=0;mypsi<360;mypsi += psi_sampling)
        for (int i=0;i<my_init;i++)
            myCounter++;

//    if (shears && XSIZE(inputVol())!=0 && VShears==NULL)
//        VShears=new RealShearsInfo(inputVol());
    if (projType == SHEARS && XSIZE(inputVol())!=0 && Vshears==NULL)
        Vshears=new RealShearsInfo(inputVol());
    if (projType == FOURIER && XSIZE(inputVol())!=0 && Vfourier==NULL)
        Vfourier=new FourierProjector(inputVol(),
        		                      paddFactor,
        		                      maxFrequency,
        		                      BSplineDeg);

    for (double mypsi=0;mypsi<360;mypsi += psi_sampling)
    {
        for (int i=my_init;i<=my_end;i++)
        {
            if (verbose)
                progress_bar(i-my_init);
            psi= mypsi+ZZ(mysampling.no_redundant_sampling_points_angles[i]);
            tilt=      YY(mysampling.no_redundant_sampling_points_angles[i]);
            rot=       XX(mysampling.no_redundant_sampling_points_angles[i]);

//            if (shears)
//                projectVolume(*VShears, P, Ydim, Xdim, rot,tilt,psi);
//            else
//                projectVolume(inputVol(), P, Ydim, Xdim, rot,tilt,psi);
            if (projType == SHEARS)
                projectVolume(*Vshears, P, Ydim, Xdim,   rot, tilt, psi);
            else if (projType == FOURIER)
                projectVolume(*Vfourier, P, Ydim, Xdim,  rot, tilt, psi);
            else if (projType == REALSPACE)
                projectVolume(inputVol(), P, Ydim, Xdim, rot, tilt, psi);


            P.setEulerAngles(rot,tilt,psi);
            P.setDataMode(_DATA_ALL);
            P.write(output_file,(size_t) (numberStepsPsi * i + mypsi +1),true,WRITE_REPLACE);
        }
    }
    if (verbose)
        progress_bar(mySize);
}
static void harmonic_coordinates_bind(Scene *UNUSED(scene), MeshDeformModifierData *mmd, MeshDeformBind *mdb)
{
	MDefBindInfluence *inf;
	MDefInfluence *mdinf;
	MDefCell *cell;
	float center[3], vec[3], maxwidth, totweight;
	int a, b, x, y, z, totinside, offset;

	/* compute bounding box of the cage mesh */
	INIT_MINMAX(mdb->min, mdb->max);

	for (a = 0; a < mdb->totcagevert; a++)
		minmax_v3v3_v3(mdb->min, mdb->max, mdb->cagecos[a]);

	/* allocate memory */
	mdb->size = (2 << (mmd->gridsize - 1)) + 2;
	mdb->size3 = mdb->size * mdb->size * mdb->size;
	mdb->tag = MEM_callocN(sizeof(int) * mdb->size3, "MeshDeformBindTag");
	mdb->phi = MEM_callocN(sizeof(float) * mdb->size3, "MeshDeformBindPhi");
	mdb->totalphi = MEM_callocN(sizeof(float) * mdb->size3, "MeshDeformBindTotalPhi");
	mdb->boundisect = MEM_callocN(sizeof(*mdb->boundisect) * mdb->size3, "MDefBoundIsect");
	mdb->semibound = MEM_callocN(sizeof(int) * mdb->size3, "MDefSemiBound");
	mdb->bvhtree = bvhtree_from_mesh_looptri(&mdb->bvhdata, mdb->cagedm, FLT_EPSILON * 100, 4, 6);
	mdb->inside = MEM_callocN(sizeof(int) * mdb->totvert, "MDefInside");

	if (mmd->flag & MOD_MDEF_DYNAMIC_BIND)
		mdb->dyngrid = MEM_callocN(sizeof(MDefBindInfluence *) * mdb->size3, "MDefDynGrid");
	else
		mdb->weights = MEM_callocN(sizeof(float) * mdb->totvert * mdb->totcagevert, "MDefWeights");

	mdb->memarena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "harmonic coords arena");
	BLI_memarena_use_calloc(mdb->memarena);

	/* initialize data from 'cagedm' for reuse */
	{
		DerivedMesh *dm = mdb->cagedm;
		mdb->cagedm_cache.mpoly = dm->getPolyArray(dm);
		mdb->cagedm_cache.mloop = dm->getLoopArray(dm);
		mdb->cagedm_cache.looptri = dm->getLoopTriArray(dm);
		mdb->cagedm_cache.poly_nors = dm->getPolyDataArray(dm, CD_NORMAL);  /* can be NULL */
	}

	/* make bounding box equal size in all directions, add padding, and compute
	 * width of the cells */
	maxwidth = -1.0f;
	for (a = 0; a < 3; a++)
		if (mdb->max[a] - mdb->min[a] > maxwidth)
			maxwidth = mdb->max[a] - mdb->min[a];

	for (a = 0; a < 3; a++) {
		center[a] = (mdb->min[a] + mdb->max[a]) * 0.5f;
		mdb->min[a] = center[a] - maxwidth * 0.5f;
		mdb->max[a] = center[a] + maxwidth * 0.5f;

		mdb->width[a] = (mdb->max[a] - mdb->min[a]) / (mdb->size - 4);
		mdb->min[a] -= 2.1f * mdb->width[a];
		mdb->max[a] += 2.1f * mdb->width[a];

		mdb->width[a] = (mdb->max[a] - mdb->min[a]) / mdb->size;
		mdb->halfwidth[a] = mdb->width[a] * 0.5f;
	}

	progress_bar(0, "Setting up mesh deform system");

	totinside = 0;
	for (a = 0; a < mdb->totvert; a++) {
		copy_v3_v3(vec, mdb->vertexcos[a]);
		mdb->inside[a] = meshdeform_inside_cage(mdb, vec);
		if (mdb->inside[a])
			totinside++;
	}

	/* free temporary MDefBoundIsects */
	BLI_memarena_free(mdb->memarena);
	mdb->memarena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "harmonic coords arena");

	/* start with all cells untyped */
	for (a = 0; a < mdb->size3; a++)
		mdb->tag[a] = MESHDEFORM_TAG_UNTYPED;
	
	/* detect intersections and tag boundary cells */
	for (z = 0; z < mdb->size; z++)
		for (y = 0; y < mdb->size; y++)
			for (x = 0; x < mdb->size; x++)
				meshdeform_add_intersections(mdb, x, y, z);

	/* compute exterior and interior tags */
	meshdeform_bind_floodfill(mdb);

	for (z = 0; z < mdb->size; z++)
		for (y = 0; y < mdb->size; y++)
			for (x = 0; x < mdb->size; x++)
				meshdeform_check_semibound(mdb, x, y, z);

	/* solve */
	meshdeform_matrix_solve(mmd, mdb);

	/* assign results */
	if (mmd->flag & MOD_MDEF_DYNAMIC_BIND) {
		mmd->totinfluence = 0;
		for (a = 0; a < mdb->size3; a++)
			for (inf = mdb->dyngrid[a]; inf; inf = inf->next)
				mmd->totinfluence++;

		/* convert MDefBindInfluences to smaller MDefInfluences */
		mmd->dyngrid = MEM_callocN(sizeof(MDefCell) * mdb->size3, "MDefDynGrid");
		mmd->dyninfluences = MEM_callocN(sizeof(MDefInfluence) * mmd->totinfluence, "MDefInfluence");
		offset = 0;
		for (a = 0; a < mdb->size3; a++) {
			cell = &mmd->dyngrid[a];
			cell->offset = offset;

			totweight = 0.0f;
			mdinf = mmd->dyninfluences + cell->offset;
			for (inf = mdb->dyngrid[a]; inf; inf = inf->next, mdinf++) {
				mdinf->weight = inf->weight;
				mdinf->vertex = inf->vertex;
				totweight += mdinf->weight;
				cell->totinfluence++;
			}

			if (totweight > 0.0f) {
				mdinf = mmd->dyninfluences + cell->offset;
				for (b = 0; b < cell->totinfluence; b++, mdinf++)
					mdinf->weight /= totweight;
			}

			offset += cell->totinfluence;
		}

		mmd->dynverts = mdb->inside;
		mmd->dyngridsize = mdb->size;
		copy_v3_v3(mmd->dyncellmin, mdb->min);
		mmd->dyncellwidth = mdb->width[0];
		MEM_freeN(mdb->dyngrid);
	}
	else {
		mmd->bindweights = mdb->weights;
		MEM_freeN(mdb->inside);
	}

	MEM_freeN(mdb->tag);
	MEM_freeN(mdb->phi);
	MEM_freeN(mdb->totalphi);
	MEM_freeN(mdb->boundisect);
	MEM_freeN(mdb->semibound);
	BLI_memarena_free(mdb->memarena);
	free_bvhtree_from_mesh(&mdb->bvhdata);
}
static void meshdeform_matrix_solve(MeshDeformModifierData *mmd, MeshDeformBind *mdb)
{
	LinearSolver *context;
	float vec[3], gridvec[3];
	int a, b, x, y, z, totvar;
	char message[256];

	/* setup variable indices */
	mdb->varidx = MEM_callocN(sizeof(int) * mdb->size3, "MeshDeformDSvaridx");
	for (a = 0, totvar = 0; a < mdb->size3; a++)
		mdb->varidx[a] = (mdb->tag[a] == MESHDEFORM_TAG_EXTERIOR) ? -1 : totvar++;

	if (totvar == 0) {
		MEM_freeN(mdb->varidx);
		return;
	}

	progress_bar(0, "Starting mesh deform solve");

	/* setup linear solver */
	context = EIG_linear_solver_new(totvar, totvar, 1);

	/* build matrix */
	for (z = 0; z < mdb->size; z++)
		for (y = 0; y < mdb->size; y++)
			for (x = 0; x < mdb->size; x++)
				meshdeform_matrix_add_cell(mdb, context, x, y, z);

	/* solve for each cage vert */
	for (a = 0; a < mdb->totcagevert; a++) {
		/* fill in right hand side and solve */
		for (z = 0; z < mdb->size; z++)
			for (y = 0; y < mdb->size; y++)
				for (x = 0; x < mdb->size; x++)
					meshdeform_matrix_add_rhs(mdb, context, x, y, z, a);

		if (EIG_linear_solver_solve(context)) {
			for (z = 0; z < mdb->size; z++)
				for (y = 0; y < mdb->size; y++)
					for (x = 0; x < mdb->size; x++)
						meshdeform_matrix_add_semibound_phi(mdb, x, y, z, a);

			for (z = 0; z < mdb->size; z++)
				for (y = 0; y < mdb->size; y++)
					for (x = 0; x < mdb->size; x++)
						meshdeform_matrix_add_exterior_phi(mdb, x, y, z, a);

			for (b = 0; b < mdb->size3; b++) {
				if (mdb->tag[b] != MESHDEFORM_TAG_EXTERIOR)
					mdb->phi[b] = EIG_linear_solver_variable_get(context, 0, mdb->varidx[b]);
				mdb->totalphi[b] += mdb->phi[b];
			}

			if (mdb->weights) {
				/* static bind : compute weights for each vertex */
				for (b = 0; b < mdb->totvert; b++) {
					if (mdb->inside[b]) {
						copy_v3_v3(vec, mdb->vertexcos[b]);
						gridvec[0] = (vec[0] - mdb->min[0] - mdb->halfwidth[0]) / mdb->width[0];
						gridvec[1] = (vec[1] - mdb->min[1] - mdb->halfwidth[1]) / mdb->width[1];
						gridvec[2] = (vec[2] - mdb->min[2] - mdb->halfwidth[2]) / mdb->width[2];

						mdb->weights[b * mdb->totcagevert + a] = meshdeform_interp_w(mdb, gridvec, vec, a);
					}
				}
			}
			else {
				MDefBindInfluence *inf;

				/* dynamic bind */
				for (b = 0; b < mdb->size3; b++) {
					if (mdb->phi[b] >= MESHDEFORM_MIN_INFLUENCE) {
						inf = BLI_memarena_alloc(mdb->memarena, sizeof(*inf));
						inf->vertex = a;
						inf->weight = mdb->phi[b];
						inf->next = mdb->dyngrid[b];
						mdb->dyngrid[b] = inf;
					}
				}
			}
		}
		else {
			modifier_setError(&mmd->modifier, "Failed to find bind solution (increase precision?)");
			error("Mesh Deform: failed to find bind solution.");
			break;
		}

		BLI_snprintf(message, sizeof(message), "Mesh deform solve %d / %d       |||", a + 1, mdb->totcagevert);
		progress_bar((float)(a + 1) / (float)(mdb->totcagevert), message);
	}

#if 0
	/* sanity check */
	for (b = 0; b < mdb->size3; b++)
		if (mdb->tag[b] != MESHDEFORM_TAG_EXTERIOR)
			if (fabsf(mdb->totalphi[b] - 1.0f) > 1e-4f)
				printf("totalphi deficiency [%s|%d] %d: %.10f\n",
				       (mdb->tag[b] == MESHDEFORM_TAG_INTERIOR) ? "interior" : "boundary", mdb->semibound[b], mdb->varidx[b], mdb->totalphi[b]);
#endif
	
	/* free */
	MEM_freeN(mdb->varidx);

	EIG_linear_solver_delete(context);
}
Esempio n. 26
0
bool Ghostscript::Install(HWND hwnd,MSGFUNC &msgfunc){
	m_installresult = false;
	if(!m_doinst)return true;
	if(!m_downloadresult)return false;
	ablib::string file = g_Setting.GetDownloadDir() + m_file.file;
	boost::filesystem::path path(file);
	CProgressBarCtrl progress_bar(::GetDlgItem(hwnd,IDC_PROGRESS));
	static const int PROGRESSBAR_MAX = 32768;

	if(file.length() < 4 || file.substr(file.length() - 4) != _T(".exe")){
		::MessageBox(hwnd,_TR("古い Ghostscript を発見しました.このバージョンには対応していません."),_T("abtlinst"),0);
		return false;
	}
	ablib::system::Process process;
	ablib::system::Process::ProcessStartInfo s;

	ablib::string gsdir;
	gsdir = g_Setting.GetInstallDir() + _T("gs");
	if(m_version != 0){
		ablib::string ver = boost::lexical_cast<ablib::string>(m_version);

		// 後ろから二つおきにピリオドを挿入
		ablib::string::size_type start = (ver.length() % 2);
		int len = ver.length();
		for(ablib::string::size_type i = 0 ; i < len/2 ; ++i){
			ver.insert(start + 3*i,_T("."));
		}
		gsdir += _T("\\gs") + ver;
	}
	
	s.Arguments = _T("\"") + file + _T("\" /S /D=") + gsdir;
//	s.Arguments = _T("\"") + file + _T("\" /D=") + g_Setting.GetInstallDir() + _T("gs");
//	s.Arg = _T("\"") + file + _T("\"");
	s.FileName = _T("");
	s.WorkingDirectory = path.parent_path().wstring();
	s.RedirectStandardError = false;
	s.RedirectStandardOutput = false;
	s.RedirectStandardInput = false;
	s.ShowState = ablib::system::Process::ProcessStartInfo::show;
	s.CreateNoWindow = false;
	process.StartInfo(s);
	CheckandSetTmp(g_Setting.GetTmpDir().c_str());
	msgfunc.msg(_T("Ghostscript のインストール\n"));
	msgfunc.detail(_T("Ghostscript をインストール中\n"));
	if(!process.Start()){
		g_Setting.Log(file + _T(" の起動に失敗"));
		return false;
	}else{
		process.WaitForExit();
	}
	
	progress_bar.SetPos(PROGRESSBAR_MAX/2);
	gsdir += _T("\\");

//	ablib::string gsdir = GetGSDir();
	if(g_Setting.SetPath()){
		if(gsdir != _T("")){
			g_Path.AddPath(gsdir + _T("bin"));
			g_Path.AddPath(gsdir + _T("lib"));
		}else g_Setting.Log(_TR("Ghostscript のインストールパス取得に失敗したので,PATH の設定を行いません"));
	}

	msgfunc.detail(_T("cidfmap の生成\n"));
	LPITEMIDLIST id;
	LPMALLOC mal;
	TCHAR fontdir[4096];
	if(
		FAILED(::SHGetMalloc(&mal)) ||
		FAILED(::SHGetSpecialFolderLocation(NULL,CSIDL_FONTS,&id)) ||
		!::SHGetPathFromIDList(id,fontdir)
	){
		g_Setting.Log(_T("cidfmap の生成に失敗(フォントフォルダの取得に失敗)."));
		return false;
	}
		
	mal->Free(id);
	if(fontdir[::lstrlen(fontdir) - 1] != '\\')::lstrcat(fontdir,_T("\\"));
	
	ablib::string arg = ablib::string(_T("-q -dBATCH -sFONTDIR=")) + fontdir + _T(" -sCIDFMAP=") + gsdir + _T("lib\\cidfmap") + _T(" ") + gsdir + _T("lib\\mkcidfm.ps");
	arg.replace(_T("\\"),_T("/"));
	s.Arguments = _T("\"") + gsdir + _T("\\bin\\gswin32c.exe\" ") + arg;
	s.WorkingDirectory = gsdir + _T("\\bin");
	process.StartInfo(s);
	if(!process.Start()){
		g_Setting.Log(s.Arguments + _T(" の実行に失敗"));
		return false;
	}else{
		process.WaitForExit();
	}
	progress_bar.SetPos(PROGRESSBAR_MAX);
	
	m_installresult = true;
	return true;
}
Esempio n. 27
0
void ProgValidationNonTilt::run()
{
    //Clustering Tendency and Cluster Validity Stephen D. Scott
    randomize_random_generator();
    MetaData md,mdGallery,mdOut,mdOut2,mdSort;
    MDRow row;

    FileName fnOut,fnOut2, fnGallery;
    fnOut = fnDir+"/clusteringTendency.xmd";
    fnGallery = fnDir+"/gallery.doc";
    fnOut2 = fnDir+"/validation.xmd";
    size_t nSamplesRandom = 500;

    md.read(fnParticles);
    mdGallery.read(fnGallery);
    mdSort.sort(md,MDL_IMAGE_IDX,true,-1,0);

    size_t maxNImg;
    size_t sz = md.size();

    if (useSignificant)
    	mdSort.getValue(MDL_IMAGE_IDX,maxNImg,sz);
    else
    {
    	mdSort.getValue(MDL_ITEM_ID,maxNImg,sz);
    }

    String expression;
    MDRow rowP,row2;
    SymList SL;
    int symmetry, sym_order;
    SL.readSymmetryFile(fnSym.c_str());
    SL.isSymmetryGroup(fnSym.c_str(), symmetry, sym_order);

/*
    double non_reduntant_area_of_sphere = SL.nonRedundantProjectionSphere(symmetry,sym_order);
    double area_of_sphere_no_symmetry = 4.*PI;
    double correction = std::sqrt(non_reduntant_area_of_sphere/area_of_sphere_no_symmetry);
*/
    double correction = 1;
    double validation = 0;
    double num_images = 0;

	MetaData tempMd;
	std::vector<double> sum_u(nSamplesRandom);
	double sum_w=0;
	std::vector<double> H0(nSamplesRandom);
	std::vector<double> H(nSamplesRandom);
	std::vector<double> p(nSamplesRandom);

	if (rank==0)
		init_progress_bar(maxNImg);

	for (size_t idx=0; idx<=maxNImg;idx++)
	{
		if ((idx)%Nprocessors==rank)
		{
			if (useSignificant)
				expression = formatString("imageIndex == %lu",idx);
			else
				expression = formatString("itemId == %lu",idx);

			tempMd.importObjects(md, MDExpression(expression));


			if (tempMd.size()==0)
				continue;

			//compute H_0 from noise
			obtainSumU_2(mdGallery, tempMd,sum_u,H0);
			//compute H from experimental
			obtainSumW(tempMd,sum_w,sum_u,H,correction);

			std::sort(H0.begin(),H0.end());
			std::sort(H.begin(),H.end());

			double P = 0;
			for(size_t j=0; j<sum_u.size();j++)
			{
				//P += H0.at(j)/H.at(j);
				P += H0.at(size_t((1-significance_noise)*nSamplesRandom))/H.at(j);
				p.at(j) = H0.at(j)/H.at(j);
			}

			P /= (nSamplesRandom);

			if (useSignificant)
				rowP.setValue(MDL_IMAGE_IDX,idx);
			else
				rowP.setValue(MDL_ITEM_ID,idx);

			rowP.setValue(MDL_WEIGHT,P);
			mdPartial.addRow(rowP);
			tempMd.clear();

			if (rank==0)
				progress_bar(idx+1);
		}
	}

	if (rank==0)
		progress_bar(maxNImg);

	synchronize();
	gatherClusterability();

	if (rank == 0)
	{
		mdPartial.write(fnOut);
		std::vector<double> P;
		mdPartial.getColumnValues(MDL_WEIGHT,P);

		for (size_t idx=0; idx< P.size();idx++)
		{
			if (P[idx] > 1)
				validation += 1.;
			num_images += 1.;
		}
		validation /= (num_images);

		row2.setValue(MDL_IMAGE,fnInit);
		row2.setValue(MDL_WEIGHT,validation);
		mdOut2.addRow(row2);
		mdOut2.write(fnOut2);
	}
}
Esempio n. 28
0
static void meshdeform_matrix_solve(MeshDeformBind *mdb)
{
	NLContext *context;
	float vec[3], gridvec[3];
	int a, b, x, y, z, totvar;
	char message[1024];

	/* setup variable indices */
	mdb->varidx= MEM_callocN(sizeof(int)*mdb->size3, "MeshDeformDSvaridx");
	for(a=0, totvar=0; a<mdb->size3; a++)
		mdb->varidx[a]= (mdb->tag[a] == MESHDEFORM_TAG_EXTERIOR)? -1: totvar++;

	if(totvar == 0) {
		MEM_freeN(mdb->varidx);
		return;
	}

	progress_bar(0, "Starting mesh deform solve");

	/* setup opennl solver */
	nlNewContext();
	context= nlGetCurrent();

	nlSolverParameteri(NL_NB_VARIABLES, totvar);
	nlSolverParameteri(NL_NB_ROWS, totvar);
	nlSolverParameteri(NL_NB_RIGHT_HAND_SIDES, 1);

	nlBegin(NL_SYSTEM);
	nlBegin(NL_MATRIX);

	/* build matrix */
	for(z=0; z<mdb->size; z++)
		for(y=0; y<mdb->size; y++)
			for(x=0; x<mdb->size; x++)
				meshdeform_matrix_add_cell(mdb, x, y, z);

	/* solve for each cage vert */
	for(a=0; a<mdb->totcagevert; a++) {
		if(a != 0) {
			nlBegin(NL_SYSTEM);
			nlBegin(NL_MATRIX);
		}

		/* fill in right hand side and solve */
		for(z=0; z<mdb->size; z++)
			for(y=0; y<mdb->size; y++)
				for(x=0; x<mdb->size; x++)
					meshdeform_matrix_add_rhs(mdb, x, y, z, a);

		nlEnd(NL_MATRIX);
		nlEnd(NL_SYSTEM);

#if 0
		nlPrintMatrix();
#endif

		if(nlSolveAdvanced(NULL, NL_TRUE)) {
			for(z=0; z<mdb->size; z++)
				for(y=0; y<mdb->size; y++)
					for(x=0; x<mdb->size; x++)
						meshdeform_matrix_add_semibound_phi(mdb, x, y, z, a);

			for(z=0; z<mdb->size; z++)
				for(y=0; y<mdb->size; y++)
					for(x=0; x<mdb->size; x++)
						meshdeform_matrix_add_exterior_phi(mdb, x, y, z, a);

			for(b=0; b<mdb->size3; b++) {
				if(mdb->tag[b] != MESHDEFORM_TAG_EXTERIOR)
					mdb->phi[b]= nlGetVariable(0, mdb->varidx[b]);
				mdb->totalphi[b] += mdb->phi[b];
			}

			if(mdb->weights) {
				/* static bind : compute weights for each vertex */
				for(b=0; b<mdb->totvert; b++) {
					if(mdb->inside[b]) {
						copy_v3_v3(vec, mdb->vertexcos[b]);
						gridvec[0]= (vec[0] - mdb->min[0] - mdb->halfwidth[0])/mdb->width[0];
						gridvec[1]= (vec[1] - mdb->min[1] - mdb->halfwidth[1])/mdb->width[1];
						gridvec[2]= (vec[2] - mdb->min[2] - mdb->halfwidth[2])/mdb->width[2];

						mdb->weights[b*mdb->totcagevert + a]= meshdeform_interp_w(mdb, gridvec, vec, a);
					}
				}
			}
			else {
				MDefBindInfluence *inf;

				/* dynamic bind */
				for(b=0; b<mdb->size3; b++) {
					if(mdb->phi[b] >= MESHDEFORM_MIN_INFLUENCE) {
						inf= BLI_memarena_alloc(mdb->memarena, sizeof(*inf));
						inf->vertex= a;
						inf->weight= mdb->phi[b];
						inf->next= mdb->dyngrid[b];
						mdb->dyngrid[b]= inf;
					}
				}
			}
		}
		else {
			error("Mesh Deform: failed to find solution.");
			break;
		}

		sprintf(message, "Mesh deform solve %d / %d       |||", a+1, mdb->totcagevert);
		progress_bar((float)(a+1)/(float)(mdb->totcagevert), message);
	}

#if 0
	/* sanity check */
	for(b=0; b<mdb->size3; b++)
		if(mdb->tag[b] != MESHDEFORM_TAG_EXTERIOR)
			if(fabs(mdb->totalphi[b] - 1.0f) > 1e-4)
				printf("totalphi deficiency [%s|%d] %d: %.10f\n",
					(mdb->tag[b] == MESHDEFORM_TAG_INTERIOR)? "interior": "boundary", mdb->semibound[b], mdb->varidx[b], mdb->totalphi[b]);
#endif
	
	/* free */
	MEM_freeN(mdb->varidx);

	nlDeleteContext(context);
}
Esempio n. 29
0
	double optimiseTransformationMatrix(bool do_optimise_nr_pairs)
	{
		std::vector<int> best_pairs_t2u, best_map;
		double score, best_score, best_dist=9999.;
		if (do_optimise_nr_pairs)
			best_score = 0.;
		else
			best_score = -999999.;

		int nn = XMIPP_MAX(1., (rotF-rot0)/rotStep);
		nn *= XMIPP_MAX(1., (tiltF-tilt0)/tiltStep);
		nn *= XMIPP_MAX(1., (xF-x0)/xStep);
		nn *= XMIPP_MAX(1., (yF-y0)/yStep);
		int n = 0;
		init_progress_bar(nn);
		for (double rot = rot0; rot <= rotF; rot+= rotStep)
		{
			for (double tilt = tilt0; tilt <= tiltF; tilt+= tiltStep)
			{
				// Assume tilt-axis lies in-plane...
				double psi = -rot;
				// Rotate all points correspondingly
				Euler_angles2matrix(rot, tilt, psi, Pass);
				//std::cerr << " Pass= " << Pass << std::endl;
				// Zero-translations for now (these are added in the x-y loops below)
				MAT_ELEM(Pass, 0, 2) = MAT_ELEM(Pass, 1, 2) = 0.;
				mapOntoTilt();
				for (int x = x0; x <= xF; x += xStep)
				{
					for (int y = y0; y <= yF; y += yStep, n++)
					{
						if (do_optimise_nr_pairs)
							score = getNumberOfPairs(x, y);
						else
							score = -getAverageDistance(x, y); // negative because smaller distance is better!

                                                bool is_best = false;
                                                if (do_optimise_nr_pairs && score==best_score)
                                                {
                                                    double dist = getAverageDistance(x, y);
                                                    if (dist < best_dist)
                                                    {
                                                        best_dist = dist;
                                                        is_best = true;
                                                    }
                                                }
						if (score > best_score || is_best)
						{
							best_score = score;
							best_pairs_t2u = pairs_t2u;
							best_rot = rot;
							best_tilt = tilt;
							best_x = x;
							best_y = y;
						}
						if (n%1000==0) progress_bar(n);
					}
				}
			}
		}
		progress_bar(nn);
		// Update pairs with the best_pairs
		if (do_optimise_nr_pairs)
			pairs_t2u = best_pairs_t2u;

		// Update the Passing matrix and the mapping
		Euler_angles2matrix(best_rot, best_tilt, -best_rot, Pass);
		// Zero-translations for now (these are added in the x-y loops below)
		MAT_ELEM(Pass, 0, 2) = MAT_ELEM(Pass, 1, 2) = 0.;
		mapOntoTilt();
		return best_score;

	}
Esempio n. 30
0
void runThread(ThreadArgument &thArg)
{
    int thread_id = thArg.thread_id;
    ProgXrayImport * ptrProg= (ProgXrayImport *)thArg.workClass;

    MetaData localMD;
    Image<double> Iaux;
    FileName fnImgIn, fnImgOut;
    size_t first = 0, last = 0;
    MultidimArray<char> mask;

    while (ptrProg->td->getTasks(first, last))
    {
        for (size_t i=first; i<=last; i++)
        {
            ptrProg->inMD.getValue(MDL_IMAGE, fnImgIn, ptrProg->objIds[i]);


            MDRow rowGeo;
            ptrProg->readGeoInfo(fnImgIn, rowGeo);
//            ptrProg->readAndCrop(fnImgIn, Iaux, ptrProg->cropSizeX, ptrProg->cropSizeY);

            Iaux.read(fnImgIn);
            Iaux().selfWindow(ptrProg->cropSizeYi,ptrProg->cropSizeXi,
            		(int)(YSIZE(Iaux())-ptrProg->cropSizeYe-1),(int)(XSIZE(Iaux())-ptrProg->cropSizeXe-1));

            Iaux().resetOrigin();




            if (XSIZE(ptrProg->IavgDark())!=0)
            {
                Iaux()-=ptrProg->IavgDark();
                forcePositive(Iaux());
            }


            double currentBeam = 1;
            double expTime = 1;
            double slitWidth = 1;

            if ( ptrProg->dSource == ptrProg->MISTRAL )
            {
                size_t idx = fnImgIn.getPrefixNumber();
                currentBeam = dMi(ptrProg->cBeamArray, idx-1);
                expTime = dMi(ptrProg->expTimeArray, idx-1);
                slitWidth = dMi(ptrProg->slitWidthArray, idx-1);
            }
            else
                ptrProg->readCorrectionInfo(fnImgIn, currentBeam, expTime, slitWidth);

            Iaux() *= 1.0/(currentBeam*expTime*slitWidth);
            if (XSIZE(ptrProg->IavgFlat())!=0)
                Iaux()/=ptrProg->IavgFlat();

            // Assign median filter to zero valued pixels to avoid -inf when applying log10
            Iaux().equal(0,mask);
            mask.resizeNoCopy(Iaux());

            if (XSIZE(ptrProg->bpMask()) != 0)
                mask += ptrProg->bpMask();

            boundMedianFilter(Iaux(), mask);

            if (ptrProg->logFix)
            {
                Iaux().selfLog();
                if (ptrProg->selfAttFix)
                    Iaux() *= -1.;
            }

            fnImgOut.compose(i+1, ptrProg->fnOut);


            size_t objId = localMD.addObject();
            localMD.setValue(MDL_IMAGE,fnImgOut,objId);
            localMD.setRow(rowGeo, objId); //
            //            localMD.setValue(MDL_ANGLE_TILT,Iaux.tilt(),objId);
            Iaux.write(fnImgOut);
            if (thread_id==0)
                progress_bar(i);
        }
    }
    //Lock for update the total counter
    ptrProg->mutex.lock();
    ptrProg->outMD.unionAll(localMD);
    ptrProg->mutex.unlock();
}