Пример #1
0
double Fit_Local_R2_Rect_Pr(Local_R2_Rect *locseg,
    const Stack *stack, const int *var_index, int nvar, int *var_link,
    double *var_min, double *var_max, double z_scale, Stack_Fit_Score *fs)
{
  if ((stack == NULL) || (locseg == NULL)) {
    TZ_ERROR(ERROR_POINTER_NULL);
  }

  double *weight = darray_malloc(LOCAL_R2_RECT_NPARAM);

  double *var = darray_malloc(LOCAL_R2_RECT_NPARAM + 1);
  var[LOCAL_R2_RECT_NPARAM] = 1.0;
  Local_R2_Rect_Param_Array(locseg, z_scale, var);

  Perceptor perceptor;
  perceptor.vs = New_Variable_Set();
  perceptor.vs->nvar = nvar;
  perceptor.vs->var_index = (int *) var_index;
  perceptor.vs->var = var;
  perceptor.vs->link = var_link;
  perceptor.min_gradient = 1e-3;

  perceptor.arg = New_Receptor_Score_Workspace();

  double *delta = (double *) Delta;
  perceptor.delta = delta;

  int i;
  for (i = 0; i < nvar; i++) {
    weight[i] = delta[var_index[i]];
  }
  double wl = darray_norm(weight, nvar);

  for (i = 0; i < nvar; i++) {
    weight[i] /= wl;
  }
  perceptor.weight = weight;


  perceptor.s =
    Make_Continuous_Function(Local_R2_Rect_Score_R,
        Local_R2_Rect_Validate, var_min, var_max);

  Fit_Perceptor(&perceptor, stack);

  for (i = 0; i < LOCAL_R2_RECT_NPARAM; i++) {
    Local_R2_Rect_Set_Var(locseg, i, perceptor.vs->var[i]);
  }
  Delete_Variable_Set(perceptor.vs);
  free(var);
  Free_Continuous_Function(perceptor.s);

  locseg->transform.theta = Normalize_Radian(locseg->transform.theta);

  Kill_Receptor_Score_Workspace((Receptor_Score_Workspace*)perceptor.arg);

  return Local_R2_Rect_Score_P(locseg, stack, z_scale, fs);
}
Пример #2
0
double Fit_Local_Bifold_Neuroseg(Local_Bifold_Neuroseg *locbn, 
				 const Stack *stack, 
				 const int *var_index, int nvar, double z_scale,
				 Stack_Fit_Score *fs)
{
  ASSERT(stack != NULL, "Null stack.");
  ASSERT(locbn != NULL, "Null segment plane.");

  double *var = darray_malloc(LOCAL_BIFOLD_NEUROSEG_NPARAM + 1);
  Local_Bifold_Neuroseg_Param_Array(locbn, z_scale, var);


  Perceptor perceptor;
  perceptor.vs = New_Variable_Set();
  perceptor.vs->nvar = nvar;
  perceptor.vs->var_index = (int *) var_index;
  perceptor.vs->var = var;
  perceptor.min_gradient = 1e-5;

  double delta[] = {0.5, 0.5, 0.5, 0.5, 1.0, 0.05, 0.015, 0.015, 0.015, 0.015, 
		    0.5, 0.5, 0.5, 0.1};
  perceptor.delta = delta;
  perceptor.weight = delta;

  double var_min[] = {1.0, 1.0, 1.0, 1.0, 1.0, 0.1, 
		      -Infinity, -Infinity, -Infinity, -Infinity, 
		      -Infinity, -Infinity, -Infinity, 0.5};
  double var_max[] = {10.0, 10.0, 10.0, 10.0, 0.9, 
		      Infinity, Infinity, Infinity, Infinity, 
		      Infinity, Infinity, Infinity, 6.0};
  perceptor.s = 
    Make_Continuous_Function(Local_Bifold_Neuroseg_Score_Gv, 
			     Local_Bifold_Neuroseg_Validate,
			     var_min, var_max);

  Fit_Perceptor(&perceptor, stack);

  int i;
  for (i = 0; i < LOCAL_BIFOLD_NEUROSEG_NPARAM; i++) {
    Local_Bifold_Neuroseg_Set_Var(locbn, i, perceptor.vs->var[i]);
  }

  Delete_Variable_Set(perceptor.vs);
  free(var);
  Free_Continuous_Function(perceptor.s);

  return Local_Bifold_Neuroseg_Score(locbn, stack, z_scale, fs);  
}
Пример #3
0
double* Unifrnd_Double_Array(int length, double *array)
{
  if (length <= 0) {
    return NULL;
  }
  
  if (array == NULL) {
    array = darray_malloc(length);
  }

  int i;
#if EXTLIB_EXIST(GSL)
  gsl_rng_init();
  for (i = 0; i < length; i++) {
    array[i] = gsl_rng_uniform(Random_Generator);
  }
#else
  for (i = 0; i < length; i++) {
    array[i] = Unifrnd();
  }  
#endif

  return array;
}
Пример #4
0
int main(int argc, char *argv[])
{
  if (Show_Version(argc, argv, "1.0") == 1) {
    return 0;
  }

  static char *Spec[] = {
    "[-R<string> -T<string> -M<string>] -D<string> [-minlen <double>]",
    "[-root <double> <double> <double>] [-trans <double> <double> <double>]",
    "[-rtlist <string>] [-sup_root] [-dist <double>]",
    "[-C<string>] [-I<string>] [-z <double>] -o <string> [-b] [-res <string>]",
    "[-screen] [-sp] [-intp] [-sl] [-rb] [-rz] [-rs] [-ct] [-al <double>]",
    "[-screenz <double>] [-force_merge <double>] [-ct_break <double>]",
    "[-jumpz <double>] [-single_break]",
    NULL};

  Print_Arguments(argc, argv);

  Process_Arguments(argc, argv, Spec, 1);
  
  char *dir = Get_String_Arg("-D");

  Stack_Document *stack_doc = NULL;
  if (Is_Arg_Matched("-I")) {
    if (!fexist(Get_String_Arg("-I"))) {
      PRINT_EXCEPTION("File does not exist", "");
      fprintf(stderr, "%s cannot be found.\n", Get_String_Arg("-I"));
      return 1;
    }
    if (fhasext(Get_String_Arg("-I"), "xml")) {
      stack_doc = Xml_Read_Stack_Document(Get_String_Arg("-I"));
    }
  }

  /* Get number of chains */
  int chain_number2 = dir_fnum_p(dir, "^chain.*\\.tb");

  if (chain_number2 == 0) {
    printf("No tube found.\n");
    printf("Quit reconstruction.\n");
    return 1;
  }

  int i;
  int *chain_map = iarray_malloc(chain_number2);
  int chain_number;
  Locseg_Chain **chain_array =
    Dir_Locseg_Chain_Nd(dir, "chain.*\\.tb", &chain_number, chain_map);

  if (Is_Arg_Matched("-screenz")) {
    Locseg_Chain_Array_Screen_Z(chain_array, chain_number,
	Get_Double_Arg("-screenz"));
  }

  if (Is_Arg_Matched("-single_break")) {
    int i;
    for (i = 0; i < chain_number; i++) {
      if (Locseg_Chain_Length(chain_array[i]) == 1) {
	/* break the segment into two parts */
	Locseg_Chain_Break_Node(chain_array[i], 0, 0.5);
      }
    }
  }

  if (Is_Arg_Matched("-ct_break")) {
    int tmp_chain_number;
    Locseg_Chain **tmp_chain_array = 
      Locseg_Chain_Array_Break_Jump(chain_array, chain_number,
	  Get_Double_Arg("-ct_break"), &tmp_chain_number);
    kill_locseg_chain_array(chain_array, chain_number);
    chain_array = tmp_chain_array;
    chain_number = tmp_chain_number;
  }

  Connection_Test_Workspace *ctw = New_Connection_Test_Workspace();
  if (Is_Arg_Matched("-res")) {
    FILE *fp = fopen(Get_String_Arg("-res"), "r");
    if (fp != NULL) {
      if (darray_fscanf(fp, ctw->resolution, 3) != 3) {
	fprintf(stderr, "Failed to load %s\n", Get_String_Arg("-res"));
	ctw->resolution[0] = 1.0;
	ctw->resolution[1] = 1.0;
	ctw->resolution[2] = 1.0;
      } else {
	ctw->unit = 'u';
      }
      fclose(fp);
    } else {
      fprintf(stderr, "Failed to load %s. The file may not exist.\n", 
	      Get_String_Arg("-res"));
    }
  } else if (stack_doc != NULL) {
    ctw->resolution[0] = stack_doc->resolution[0];
    ctw->resolution[1] = stack_doc->resolution[1];
    ctw->resolution[2] = stack_doc->resolution[2];
  }

  if (Is_Arg_Matched("-force_merge")) {
    Connection_Test_Workspace *ws = New_Connection_Test_Workspace();
    ws->dist_thre = Get_Double_Arg("-force_merge");
    ws->interpolate = FALSE;
    ws->resolution[2] = ctw->resolution[2] / ctw->resolution[0];
    for (i = 0; i < chain_number; i++) {
      //Locseg_Chain_Correct_Ends(chain_array[i]); 
    }
    Locseg_Chain_Array_Force_Merge(chain_array, chain_number, ws); 
    Kill_Connection_Test_Workspace(ws);
  }

  chain_number2 = 0;
  Neuron_Component *chain_array2;
  GUARDED_MALLOC_ARRAY(chain_array2, chain_number, Neuron_Component); 
  for (i = 0; i < chain_number; i++) {
    if (Locseg_Chain_Is_Empty(chain_array[i]) == FALSE) {
      chain_map[chain_number2] = chain_map[i];
      Set_Neuron_Component(chain_array2+(chain_number2++), 
	  NEUROCOMP_TYPE_LOCSEG_CHAIN, chain_array[i]);
    } else {
      printf("chain_%d is empty.\n", chain_map[i]);
    }
  }
    /*
    Dir_Locseg_Chain_Nc(dir, "^chain.*\\.tb", &chain_number2, chain_map);
*/
  Stack *signal = NULL;
  //Stack *canvas = NULL;
  if (Is_Arg_Matched("-I")) {
    signal = Read_Stack_U(Get_String_Arg("-I"));
    //canvas = Translate_Stack(signal, COLOR, 0);
  } else {
    if (Is_Arg_Matched("-screen")) {
      perror("The -screen option requires -I option to be supplied.\n");
      return 1;
    }
  }

  /* Minimal tube length. */
  double minlen = 25.0;
  if (Is_Arg_Matched("-minlen")) {
    minlen = Get_Double_Arg("-minlen");
  }

  chain_number = 0;
  //int i;


  if (signal != NULL) {
    ctw->mask = Make_Stack(GREY, signal->width, signal->height, signal->depth);
    One_Stack(ctw->mask);
  }

  FILE *result_file = fopen(full_path(dir, Get_String_Arg("-o")), "w");


  double z_scale = 1.0;
  if (Is_Arg_Matched("-z")) {
    z_scale = Get_Double_Arg("-z");
  }


  /* Array to store corrected chains */
  Neuron_Component *chain_array_c = Make_Neuron_Component_Array(chain_number2);

  int screen = 0;

  double average_intensity = 0.0;

  if (Is_Arg_Matched("-screen")) {
    int good_chain_number = 0;
    int bad_chain_number = 0;
    for (i = 0; i < chain_number2; i++) {
      Locseg_Chain *chain = NEUROCOMP_LOCSEG_CHAIN(chain_array2 + i);

      average_intensity += Locseg_Chain_Average_Score(chain, signal, z_scale, 
						      STACK_FIT_MEAN_SIGNAL);

      if ((Locseg_Chain_Geolen(chain) > 55) || 
	  (Locseg_Chain_Average_Score(chain, signal, z_scale, 
				      STACK_FIT_CORRCOEF) > 0.6)) {
	good_chain_number++;
      } else {
	bad_chain_number++;
      }
    }
    
    printf("good %d bad %d\n", good_chain_number, bad_chain_number);

    if (good_chain_number + bad_chain_number > 50) {
      if (bad_chain_number > good_chain_number) {
	screen = 1;
      }
    } else {
      screen = 3;
      /*
      if (bad_chain_number > good_chain_number * 2) {
	screen = 2;
      }
      */
    }
  }

  average_intensity /= chain_number2;

  /* build chain map */
  for (i = 0; i < chain_number2; i++) {
    Locseg_Chain *chain = NEUROCOMP_LOCSEG_CHAIN(chain_array2 + i);
    BOOL good = FALSE;
    
    switch (screen) {
    case 1:
    case 2:
      if ((Locseg_Chain_Geolen(chain) > 100) || 
	  (Locseg_Chain_Average_Score(chain, signal, z_scale, 
				      STACK_FIT_CORRCOEF)
	   > 0.6)) {
	good = TRUE;
      } else {
	if (Locseg_Chain_Geolen(chain) < 100) {
	  if ((Locseg_Chain_Average_Score(chain, signal, z_scale, 
					 STACK_FIT_CORRCOEF) > 0.5) ||
	      (Locseg_Chain_Average_Score(chain, signal, z_scale, 
					  STACK_FIT_MEAN_SIGNAL) > 
	       average_intensity)) {
	    good = TRUE;
	  }
	}
      }
      break;
    case 3:
      if ((Locseg_Chain_Average_Score(chain, signal, z_scale, 
				      STACK_FIT_CORRCOEF) > 0.50) ||
	  (Locseg_Chain_Average_Score(chain, signal, z_scale, 
				      STACK_FIT_MEAN_SIGNAL) > 
	   average_intensity)) {
	good = TRUE;
      }
      break;
    default:
      good = TRUE;
    }

    if (good == TRUE) {
      if (Locseg_Chain_Geolen(chain) < minlen) {
	good = FALSE;
      }
    }

    if (good == TRUE) {
      Locseg_Chain *tmpchain = chain;
      if (signal != NULL) {
	//Locseg_Chain_Trace_Np(signal, 1.0, tmpchain, tw);
	Locseg_Chain_Erase(chain, ctw->mask, 1.0);
      }
      fprintf(result_file, "%d %d\n", chain_number, chain_map[i]);
      chain_map[chain_number] = chain_map[i];
      if (z_scale != 1.0) {
	Locseg_Chain_Scale_Z(chain, z_scale);
      }
      Set_Neuron_Component(chain_array_c + chain_number, 
			   NEUROCOMP_TYPE_LOCSEG_CHAIN, tmpchain);
      chain_number++;
    } else {
#ifdef _DEBUG_
      printf("chain%d is excluded.\n", i);
      /*
      char tmpfile[500];
      sprintf(tmpfile, "../data/diadem_c1/bad_chain/chain%d.tb", i);
      Write_Locseg_Chain(tmpfile, chain);
      */
#endif
    }
  }

  z_scale = 1.0;

  fprintf(result_file, "#\n");

  //Int_Arraylist *hit_spots = Int_Arraylist_New(0, chain_number);
  /* reconstruct neuron */

  if (Is_Arg_Matched("-res")) {
    FILE *fp = fopen(Get_String_Arg("-res"), "r");
    if (fp != NULL) {
      if (darray_fscanf(fp, ctw->resolution, 3) != 3) {
	fprintf(stderr, "Failed to load %s\n", Get_String_Arg("-res"));
	ctw->resolution[0] = 1.0;
	ctw->resolution[1] = 1.0;
	ctw->resolution[2] = 1.0;
      } else {
	ctw->unit = 'u';
      }
      fclose(fp);
    } else {
      fprintf(stderr, "Failed to load %s. The file may not exist.\n", 
	      Get_String_Arg("-res"));
    }
  } else if (stack_doc != NULL) {
    ctw->resolution[0] = stack_doc->resolution[0];
    ctw->resolution[1] = stack_doc->resolution[1];
    ctw->resolution[2] = stack_doc->resolution[2];
  }

  if (!Is_Arg_Matched("-sp")) {
    ctw->sp_test = FALSE;
    if (ctw->sp_test == FALSE) {
      ctw->dist_thre = NEUROSEG_DEFAULT_H / 2.0;
    }
  } else {
    ctw->dist_thre = NEUROSEG_DEFAULT_H * 1.5;
  }
  
  if (Is_Arg_Matched("-dist")) {
    ctw->dist_thre = Get_Double_Arg("-dist");
  }

  if (!Is_Arg_Matched("-intp")) {
    ctw->interpolate = FALSE;
  }
  //ctw->dist_thre = 100.0;

  double *tube_offset = NULL;
  if (Is_Arg_Matched("-trans")) {
    tube_offset = darray_malloc(3);
    tube_offset[0] = Get_Double_Arg("-trans", 1);
    tube_offset[1] = Get_Double_Arg("-trans", 2);
    tube_offset[2] = Get_Double_Arg("-trans", 3);
  } else {
    if (stack_doc != NULL) {
      tube_offset = darray_malloc(3);
      tube_offset[0] = stack_doc->offset[0];
      tube_offset[1] = stack_doc->offset[1];
      tube_offset[2] = stack_doc->offset[2];
    }
  }

  Neuron_Structure *ns = New_Neuron_Structure();
  ns->comp = chain_array_c;
  ns->graph = New_Graph();
  ns->graph->nvertex = chain_number;
  
  if (Is_Arg_Matched("-rtlist")) {
    int m, n;
    double *d = darray_load_matrix(Get_String_Arg("-rtlist"), NULL, &m, &n);

    if (n > 0) {
      coordinate_3d_t *roots = GUARDED_MALLOC_ARRAY(roots, n, coordinate_3d_t);
      int i;
      for (i = 0; i < n; i++) {
	if (Is_Arg_Matched("-trans")) {
	  roots[i][0] = d[i*3] - tube_offset[0];
	  roots[i][1] = d[i*3 + 1] - tube_offset[1];
	  roots[i][2] = d[i*3 + 2] - tube_offset[2];
	} else {
	  roots[i][0] = d[i*3];
	  roots[i][1] = d[i*3 + 1];
	  roots[i][2] = d[i*3 + 2];
	}
      }

      Neuron_Structure_Break_Root(ns, roots, n);
      Neuron_Structure_Load_Root(ns, roots, n);
    }
  }
  
  Locseg_Chain_Comp_Neurostruct_W(ns, signal, z_scale, ctw);

  if (tube_offset != NULL) {
    for (i = 0; i < chain_number; i++) {
      Locseg_Chain_Translate(NEUROCOMP_LOCSEG_CHAIN(chain_array_c + i), 
			     tube_offset);
    }
  }

  /*  
  Neuron_Structure *ns = Locseg_Chain_Comp_Neurostruct(chain_array, 
						       chain_number,
						       signal, z_scale, ctw);
  */

  FILE *tube_fp = fopen(full_path(dir, "tube.swc"), "w");
  int start_id = 1;

  for (i = 0; i < chain_number; i++) {
    int node_type = i % 10;
    int n = Locseg_Chain_Swc_Fprint_T(tube_fp, 
				      NEUROCOMP_LOCSEG_CHAIN(chain_array_c + i), 
				      node_type, start_id, 
				      -1, DL_FORWARD, 1.0, NULL);
    start_id += n;
  }
  fclose(tube_fp);

  //Neuron_Structure_To_Swc_File(ns, full_path(dir, "tube.swc"));
  /*
  Graph *testgraph = New_Graph(0, 0, FALSE);
  Int_Arraylist *cidx = Make_Int_Arraylist(0, 2);
  Int_Arraylist *sidx = Make_Int_Arraylist(0, 2);
  
  Locseg_Chain_Network_Simlify(&net, testgraph, cidx, sidx);
  */

  /* Find branch points */
  //Locseg_Chain *branches = Locseg_Chain_Network_Find_Branch(ns);

  //Graph *graph = Locseg_Chain_Graph(chain_array, chain_number, hit_spots);
  //Graph *graph = ns->graph;

  if (Is_Arg_Matched("-sup_root")) {
    if (Is_Arg_Matched("-rtlist")) {
      int m, n;
      double *d = darray_load_matrix(Get_String_Arg("-rtlist"), NULL, &m, &n);
      
      if (n > 0) {
	coordinate_3d_t *roots = 
	  GUARDED_MALLOC_ARRAY(roots, n, coordinate_3d_t);
	int i;
	for (i = 0; i < n; i++) {
	  roots[i][0] = d[i*3];
	  roots[i][1] = d[i*3 + 1];
	  roots[i][2] = d[i*3 + 2];
	  /*
	  if (tube_offset != NULL) {
	    roots[i][0] += tube_offset[0];
	    roots[i][1] += tube_offset[1];
	    roots[i][2] += tube_offset[2];
	  }
	  */
	}
	neuron_structure_suppress(ns, roots, n);
	free(roots);
      }
    }
  }

  Process_Neuron_Structure(ns);

  Print_Neuron_Structure(ns);

#ifdef _DEBUG_
  for (i = 0; i < NEURON_STRUCTURE_LINK_NUMBER(ns); i++) {
    printf("chain_%d (%d) -- chain_%d (%d) ", 
	chain_map[ns->graph->edges[i][0]], 
	ns->graph->edges[i][0], 
	chain_map[ns->graph->edges[i][1]],
	ns->graph->edges[i][1]);
    Print_Neurocomp_Conn(ns->conn + i);
  }
#endif

  if (Is_Arg_Matched("-ct")) {
    Neuron_Structure_Crossover_Test(ns, 
				    ctw->resolution[0] / ctw->resolution[2]);
  }

  if (Is_Arg_Matched("-al")) {
    Neuron_Structure_Adjust_Link(ns, Get_Double_Arg("-al"));
  }

  Neuron_Structure_To_Tree(ns);
  Neuron_Structure_Remove_Negative_Conn(ns);

#ifdef _DEBUG_
  printf("\nTree:\n");
  for (i = 0; i < NEURON_STRUCTURE_LINK_NUMBER(ns); i++) {
    printf("chain_%d (%d) -- chain_%d (%d) ", 
	chain_map[ns->graph->edges[i][0]], 
	ns->graph->edges[i][0], 
	chain_map[ns->graph->edges[i][1]],
	ns->graph->edges[i][1]);
    Print_Neurocomp_Conn(ns->conn + i);
  }
#endif
  /*
  printf("\ncross over changed: \n");
  Print_Neuron_Structure(ns);
  */

#ifdef _DEBUG_2
  ns->graph->nedge = 0;
  Neuron_Structure_To_Swc_File(ns, "../data/test.swc"); 
  return 1;
#endif
  
  //Print_Neuron_Structure(ns);

  
  Neuron_Structure* ns2= NULL;
  
  if (Is_Arg_Matched("-intp")) {
    ns2 = Neuron_Structure_Locseg_Chain_To_Circle_S(ns, 1.0, 1.0);
  } else {
    ns2 = Neuron_Structure_Locseg_Chain_To_Circle(ns);
  }
    
  /*
  Neuron_Structure* ns2=
    Neuron_Structure_Locseg_Chain_To_Circle_S(ns, 1.0, 1.0);
  */
  Graph_To_Dot_File(ns2->graph, full_path(dir, "graph_d.dot"));

  //Neuron_Structure_Main_Graph(ns2);
  Neuron_Structure_To_Tree(ns2);
  
  double root[3];

  if (Is_Arg_Matched("-root")) {
    root[0] = Get_Double_Arg("-root", 1);
    root[1] = Get_Double_Arg("-root", 2);
    root[2] = Get_Double_Arg("-root", 3);
  }

  Swc_Tree *tree = NULL;

  if (Is_Arg_Matched("-root")) {
    /*
    int root_index = Neuron_Structure_Find_Root_Circle(ns2, root);
    Graph_Workspace *gw2 = New_Graph_Workspace();
    Graph_Clean_Root(ns2->graph, root_index, gw2);

    Neuron_Structure_To_Swc_File_Circle_Z(ns2, full_path(dir, "graph_d.swc"),
					  z_scale, root);
    */
    tree = Neuron_Structure_To_Swc_Tree_Circle_Z(ns2, z_scale, root);
    if (Swc_Tree_Node_Is_Virtual(tree->root) == TRUE) {
      tree->root->first_child->next_sibling = NULL;
    }
    Swc_Tree_Clean_Root(tree);
  } else {
    /*
    Neuron_Structure_To_Swc_File_Circle_Z(ns2, full_path(dir, "graph_d.swc"),
					  z_scale, NULL);
    */
    tree = Neuron_Structure_To_Swc_Tree_Circle_Z(ns2, z_scale, NULL);
  }

  ns->graph->nedge = 0;
  //Neuron_Structure_To_Swc_File(ns, full_path(dir, "tube.swc"));


  if (Is_Arg_Matched("-rb")) {
    //Swc_Tree_Tune_Branch(tree);
    Swc_Tree_Tune_Fork(tree);
  }

  if (Is_Arg_Matched("-sl")) {
    Swc_Tree_Leaf_Shrink(tree);
  }

  if (Is_Arg_Matched("-rz")) {
    Swc_Tree_Remove_Zigzag(tree);
  }

  if (Is_Arg_Matched("-rs")) {
    Swc_Tree_Remove_Spur(tree);
  }
  
  Swc_Tree_Resort_Id(tree);

  Write_Swc_Tree(full_path(dir, "graph_d.swc"), tree);

  if (Is_Arg_Matched("-rtlist")) {
    int m, n;
    double *d = darray_load_matrix(Get_String_Arg("-rtlist"), NULL, &m, &n);

    if (n > 0) {
      coordinate_3d_t *roots = GUARDED_MALLOC_ARRAY(roots, n, coordinate_3d_t);
      int i;
      for (i = 0; i < n; i++) {
	roots[i][0] = d[i*3];
	roots[i][1] = d[i*3 + 1];
	roots[i][2] = d[i*3 + 2];

	/*
	if (tube_offset != NULL) {
	  roots[i][0] += tube_offset[0];
	  roots[i][1] += tube_offset[1];
	  roots[i][2] += tube_offset[2];
	}
	*/

	Swc_Tree *subtree = Swc_Tree_Pull_R(tree, roots[i]);
	char filename[MAX_PATH_LENGTH];
	if (subtree->root != NULL) {
	  //Swc_Tree_Clean_Root(subtree);
	  Swc_Tree_Clean_Root(subtree);
	  Swc_Tree_Node_Set_Pos(subtree->root, roots[i]);
	  if (Is_Arg_Matched("-jumpz")) {
	    //swc_tree_remove_zjump(subtree, Get_Double_Arg("-jumpz"));
	  }
	  Swc_Tree_Resort_Id(subtree);
	  sprintf(filename, "graph%d.swc", i + 1);
	  Write_Swc_Tree(full_path(dir, filename), subtree);
	}
      }
    }
  }

  printf("%d chains\n", chain_number);

  return 0;
}
Пример #5
0
void Trace_Evaluate_Seed(const Geo3d_Scalar_Field *seed,
                         const Stack *signal, double z_scale,
                         Trace_Evaluate_Seed_Workspace *ws)
{
    OBJECT_SAFE_FREE(ws->score, free);
    ws->score = darray_malloc(seed->size);

    int i;
    OBJECT_SAFE_FREE(ws->locseg, free);
    ws->locseg = (Local_Neuroseg *) malloc(seed->size * sizeof(Local_Neuroseg));

    ws->nseed = seed->size;

    int index = 0;

    if (ws->base_mask == NULL) {
        ws->base_mask = Make_Stack(GREY, signal->width, signal->height,
                                   signal->depth);
        Zero_Stack(ws->base_mask);
    }

    for (i = 0; i < seed->size; i++) {
        printf("-----------------------------> seed: %d / %d\n", i, seed->size);

        index = i;
        int x = (int) seed->points[index][0];
        int y = (int) seed->points[index][1];
        int z = (int) seed->points[index][2];

        if (ws->zshift) {
            stack_adjust_zpos(signal, x, y, &z);
            if (ws->trace_mask != NULL) {
                if (Stack_Pixel(ws->trace_mask, x, y, z, 0) > 0.0) {
                    printf("traced**\n");
                    ws->score[i] = 0.0;
                    continue;
                }
            }
        }

        double width = seed->values[index];

        int seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height,
                                            signal->depth);

        if (width < 3.0) {
            width += 0.5;
        }
        Set_Neuroseg(&(ws->locseg[i].seg), width, 0.0, NEUROSEG_DEFAULT_H,
                     0.0, 0.0, 0.0, 0.0, 1.0);

        double cpos[3];
        cpos[0] = x;
        cpos[1] = y;
        cpos[2] = z;
        cpos[2] /= z_scale;

        Set_Neuroseg_Position(&(ws->locseg[i]), cpos, NEUROSEG_CENTER);

        if (ws->base_mask->array[seed_offset] > 0) {
            printf("labeled\n");
            ws->score[i] = 0.0;
            continue;
        }

        {   /* for faster evaluation*/
            Local_Neuroseg *locseg = ws->locseg + i;
            Stack_Fit_Score fs;
            fs.n = 1;
            fs.options[0] = STACK_FIT_CORRCOEF;

            Locseg_Fit_Workspace *fw = (Locseg_Fit_Workspace*) ws->fws;

            int k;
            for (k = 0; k < fw->pos_adjust; k++) {
                Local_Neuroseg_Position_Adjust(locseg, signal, z_scale);
            }

            Local_Neuroseg_Orientation_Search_C(locseg, signal, z_scale, &fs);

            if (ws->fit_option <= 1) {
                for (k = 0; k < 3; k++) {
                    Local_Neuroseg_Position_Adjust(locseg, signal, z_scale);
                }
            }

            double bpos[3];
            double tpos[3];
            Local_Neuroseg_Bottom(locseg, bpos);
            Local_Neuroseg_Center(locseg, cpos);
            Local_Neuroseg_Top(locseg, tpos);
            if (ws->trace_mask != NULL) {
                if ((Stack_Pixel(ws->trace_mask, bpos[0], bpos[1], bpos[2], 0) > 0) &&
                        (Stack_Pixel(ws->trace_mask, cpos[0], cpos[1], cpos[2], 0) > 0) &&
                        (Stack_Pixel(ws->trace_mask, tpos[0], tpos[1], tpos[2], 0) > 0)) {
                    printf("traced*\n");
                    ws->score[i] = 0.0;
                    continue;
                }
            }

            if ((ws->fit_option == 1) || (ws->fit_option == 2)) {
                Local_Neuroseg_R_Scale_Search(locseg, signal, z_scale, 1.0, 10.0, 1.0,
                                              0.5, 5.0, 0.5, NULL);
            }

            Fit_Local_Neuroseg_W(locseg, signal, z_scale, fw);
        }

        if (ws->trace_mask != NULL) {
            if (Local_Neuroseg_Hit_Mask(ws->locseg + i,
                                        ws->trace_mask, z_scale) > 0) {
                printf("traced\n");
                ws->score[i] = 0.0;
                continue;
            }
        }

        //ws->score[i] = Local_Neuroseg_Score(ws->locseg + i, signal, z_scale, &fs);
        ws->score[i] = ws->fws->sws->fs.scores[1];

        printf("%g\n", ws->score[i]);

        if (Local_Neuroseg_Good_Score(ws->locseg + i, ws->score[i], ws->min_score)
                == TRUE) {
            Local_Neuroseg_Label_G(ws->locseg + i, ws->base_mask, -1, 2, z_scale);
        } else {
            Local_Neuroseg_Label_G(ws->locseg + i, ws->base_mask, -1, 1, z_scale);
        }
    }
}
Пример #6
0
int* Int_Histogram_Equal_Info_Map(const int *hist, int nbin, int *map)
{
  int length = Int_Histogram_Length(hist);
  int min = Int_Histogram_Min(hist);

  if (map == NULL) {
    map = iarray_malloc(length);
  }

  const int *hist_array = Int_Histogram_Const_Array(hist);
  
  /* alloc <info> */
  double *info = darray_malloc(length);
  
  int i;

  for (i = 0; i < length; i++) {
    if (hist_array[i] == 0) {
      info[i] = 0;
    } else {
      if (min +i == 0) {
	info[i] = log(hist_array[i]);
      } else
	info[i] = log(hist_array[i]) + log(min + i);
    }
  }

  double total_number = darray_sum(info, length);
  int current_index = 0;
  double threshold = total_number / nbin;
  double count = info[0];

  map[0] = current_index;
  for (i = 1; i < length; i++) {
    if (nbin - map[i-1] - 1 >= length - i) {
      int j;
      current_index = map[i-1] + 1;
      for (j = i; j < length; j++) {
	map[j] = current_index++;
      }
      break;
    }

    count += info[i];
    if (count <= threshold) {
      map[i] = current_index;
    } else {
      total_number -= count;
      if (count - threshold >= threshold + info[i] - count) {
	total_number += info[i];
	count = info[i];
	map[i] = current_index + 1;
      } else {
	count = 0;
	map[i] = current_index;
      }

      current_index++;

      /* this case should not happen */
      if (current_index > 255) {
	current_index = 255;
      }

      /* update threshold */
      threshold = total_number / (nbin - current_index);
    }
  }

  /* free <info> */
  free(info);

  return map;
}
Пример #7
0
int* Stack_Graph_Shortest_Path(const Stack *stack, int start[], int end[],
			       Stack_Graph_Workspace *sgw)
{
  int start_index = Stack_Util_Offset(start[0], start[1], start[2], 
				      stack->width, stack->height, 
				      stack->depth);
  int end_index = Stack_Util_Offset(end[0], end[1], end[2], 
				    stack->width, stack->height, 
				    stack->depth);

  int nvoxel = Stack_Voxel_Number(stack);
  int *path = iarray_malloc(nvoxel);
  double *dist = darray_malloc(nvoxel);
  int *checked = iarray_malloc(nvoxel);

  int i, j;

  for (i = 0; i < nvoxel; i++) {
    dist[i] = Infinity;
    path[i] = -1;
    checked[i] = 0;
  }

  dist[start_index] = 0;
  path[start_index] = -1;
  checked[start_index] = 1;
  
  int prev_vertex = start_index;
  int cur_vertex = start_index;
  int updating_vertex;
  double tmpdist;

  int neighbor[26];
  Stack_Neighbor_Offset(sgw->conn, stack->width, stack->height, neighbor);
  const double *neighbor_dist = Stack_Neighbor_Dist(sgw->conn);

  int is_in_bound[26];
  int nbound;

  Int_Arraylist *heap = Int_Arraylist_New(1, 0);
  int cwidth = stack->width - 1;
  int cheight = stack->height - 1;
  int cdepth = stack->depth - 1;

  void *argv[3];
  double v1;
  double v2;
  double d;
  argv[0] = &v1;
  argv[1] = &v2;
  argv[2] = &d;

  for (i = 1; i < nvoxel; i++) {
    prev_vertex = cur_vertex;
    nbound = Stack_Neighbor_Bound_Test_I(sgw->conn, cwidth, cheight, cdepth, 
					 cur_vertex, is_in_bound);
    
    if (nbound == sgw->conn) {
      for (j = 0; j < sgw->conn; j++) {
	updating_vertex = cur_vertex + neighbor[j];
	if (checked[updating_vertex] != 1) {
	  v1 = Stack_Array_Value(stack, cur_vertex);
	  v2 = Stack_Array_Value(stack, updating_vertex);
	  d = neighbor_dist[j];
	  double weight = sgw->wf(argv);
	  tmpdist = weight + dist[cur_vertex];
	  if (dist[updating_vertex] > tmpdist) {
	    dist[updating_vertex] = tmpdist;
	    path[updating_vertex] = cur_vertex;
	    
	    if (checked[updating_vertex] > 1) {
	      Int_Heap_Update_I(heap, updating_vertex, dist, checked);
	    } else {
	      Int_Heap_Add_I(heap, updating_vertex, dist, checked);
	    }
	  }
	}
      }
    } else {
      for (j = 0; j < sgw->conn; j++) {
	if (is_in_bound[j]) {
	  updating_vertex = cur_vertex + neighbor[j];
	  if (checked[updating_vertex] != 1) {
	    v1 = Stack_Array_Value(stack, cur_vertex);
	    v2 = Stack_Array_Value(stack, updating_vertex);
	    d = neighbor_dist[j];
	    double weight = sgw->wf(argv);
	    tmpdist = weight + dist[cur_vertex];
	    if (dist[updating_vertex] > tmpdist) {
	      dist[updating_vertex] = tmpdist;
	      path[updating_vertex] = cur_vertex;
	    
	      if (checked[updating_vertex] > 1) {
		Int_Heap_Update_I(heap, updating_vertex, dist, checked);
	      } else {
		Int_Heap_Add_I(heap, updating_vertex, dist, checked);
	      }
	    }
	  }
	}
      }
    }

    cur_vertex = extract_min(dist, checked, nvoxel, heap);

    if (cur_vertex == end_index) {
      break;
    }

    if (cur_vertex < 0) {
      break;
    }
  }

  Kill_Int_Arraylist(heap);
  free(checked);
  free(dist);

  return path;  
}
Пример #8
0
Graph* Stack_Graph_W(const Stack *stack, Stack_Graph_Workspace *sgw)
{
  int x, y, z;
  int offset = 0;
  int is_in_bound[26];
  int nbound;
  int i;
  int stack_range[6];

  int *range = sgw->range;

  if (range == NULL) {
    stack_range[0] = 0;
    stack_range[1] = stack->width - 1;
    stack_range[2] = 0;
    stack_range[3] = stack->height - 1;
    stack_range[4] = 0;
    stack_range[5] = stack->depth - 1;
  } else {
    stack_range[0] = imax2(0, range[0]);
    stack_range[1] = imin2(stack->width - 1, range[1]);
    stack_range[2] = imax2(0, range[2]);
    stack_range[3] = imin2(stack->height - 1, range[3]);
    stack_range[4] = imax2(0, range[4]);
    stack_range[5] = imin2(stack->depth - 1, range[5]);
  }
  
  int cdepth = stack_range[5] - stack_range[4];
  int cheight = stack_range[3] - stack_range[2];
  int cwidth = stack_range[1] - stack_range[0];
  
  int nvertex = (cwidth + 1) * (cheight + 1) * (cdepth + 1);
  sgw->virtualVertex = nvertex;

  BOOL weighted = TRUE;
  if (sgw->sp_option == 1) {
    weighted = FALSE;
    sgw->intensity = darray_malloc(nvertex + 1);
    sgw->intensity[nvertex] = Infinity;
  }
  Graph *graph = Make_Graph(nvertex, nvertex, weighted);

  int neighbor[26];
  int scan_mask[26];
  Stack_Neighbor_Offset(sgw->conn, cwidth + 1, cheight + 1, neighbor);

  int org_neighbor[26];
  Stack_Neighbor_Offset(sgw->conn, Stack_Width(stack), Stack_Height(stack), 
      org_neighbor);

  double dist[26];
  Stack_Neighbor_Dist_R(sgw->conn, sgw->resolution, dist);
  //const double *dist = Stack_Neighbor_Dist(sgw->conn);
  const int *x_offset = Stack_Neighbor_X_Offset(sgw->conn);
  const int *y_offset = Stack_Neighbor_Y_Offset(sgw->conn);
  const int *z_offset = Stack_Neighbor_Z_Offset(sgw->conn);

  /* go forward */
  for (i = 0; i < sgw->conn; i++) {
    scan_mask[i] = (neighbor[i] > 0);
  }

#define STACK_GRAPH_ADD_EDGE(cond) \
  for (i = 0; i < sgw->conn; i++) { \
    if (cond) { \
      int nx = x + stack_range[0]; \
      int ny = y + stack_range[2]; \
      int nz = z + stack_range[4]; \
      if (Graph_Is_Weighted(graph)) { \
	double weight = dist[i]; \
	if (sgw->wf != NULL) { \
	  sgw->argv[0] = dist[i]; \
	  \
	  sgw->argv[1] = Get_Stack_Pixel((Stack *)stack, nx, ny, nz, 0); \
	  sgw->argv[2] = \
	  Get_Stack_Pixel((Stack *)stack, nx + x_offset[i], \
	      ny + y_offset[i], nz + z_offset[i], 0); \
	  weight = sgw->wf(sgw->argv); \
	} \
	Graph_Add_Weighted_Edge(graph, offset, offset + neighbor[i], \
	    weight); \
      } else { \
	Graph_Add_Edge(graph, offset, offset + neighbor[i]); \
	sgw->intensity[offset] = Get_Stack_Pixel((Stack*) stack, \
	      nx, ny, nz, 0); \
      } \
    } \
  }

  int groupVertexMap[256];
  for (i = 0; i < 256; ++i) {
    groupVertexMap[i] = 0;
  }

  int swidth = cwidth + 1;
  int sarea =  (cwidth + 1) * (cheight + 1);
  int area = stack->width * stack->height;
  for (z = 0; z <= cdepth; z++) {
    for (y = 0; y <= cheight; y++) {
      for (x = 0; x <= cwidth; x++) {
	nbound = Stack_Neighbor_Bound_Test_S(sgw->conn, cwidth, cheight, 
					     cdepth, 
					     x, y, z, is_in_bound);
	size_t offset2 = Stack_Subindex((size_t) offset, stack_range[0],
	    stack_range[2], stack_range[4],
	    swidth, sarea, stack->width, area);

#ifdef _DEBUG_2
        if (offset == 36629) {
          printf("debug here\n");
        }
#endif

	if (nbound == sgw->conn) {
	  STACK_GRAPH_ADD_EDGE((scan_mask[i] == 1) && 
              (sgw->signal_mask == NULL ? 1 : 
               ((sgw->signal_mask->array[offset2] > 0) &&
                (sgw->signal_mask->array[offset2+org_neighbor[i]] > 0))))
	} else {
	  STACK_GRAPH_ADD_EDGE((scan_mask[i] == 1) && is_in_bound[i] && 
	      (sgw->signal_mask == NULL ? 1 : 
	       ((sgw->signal_mask->array[offset2] > 0) &&
		(sgw->signal_mask->array[offset2+org_neighbor[i]]) >
		0)))
	}
	if (sgw->group_mask != NULL) {
          int groupId = sgw->group_mask->array[offset2];
	  if (groupId > 0) {
#ifdef _DEBUG_2
	    sgw->group_mask->array[offset2] = 2;
#endif
            int groupVertex = groupVertexMap[groupId];
            if (groupVertex <= 0) {
              groupVertex = nvertex++;
              groupVertexMap[groupId] = groupVertex;
            }

            Graph_Add_Weighted_Edge(graph, groupVertex, offset, 0.0);
	  }
	}

	offset++;
      }
    }
  }

  return graph;
}
Пример #9
0
int main(int argc, char* argv[])
{
  if (Show_Version(argc, argv, "1.00") == 1) {
    return 0;
  }

  static char *Spec[] = {
    " <image:string> -s <string> -o <string> [-e <string>] [-fo <int>] "
    "[-z <double> | -res <string>] [-field <int>] [-min_score <double>]",
    NULL};
  
  Process_Arguments(argc, argv, Spec, 1);
  
  Geo3d_Scalar_Field *seed = Read_Geo3d_Scalar_Field(Get_String_Arg("-s"));

  size_t idx;
  double max_r = darray_max(seed->values, seed->size, &idx);

  max_r *= 1.5;

  //Set_Neuroseg_Max_Radius(max_r);

  Stack *signal = Read_Stack_U(Get_String_Arg("image"));

  dim_type dim[3];
  dim[0] = signal->width;
  dim[1] = signal->height;
  dim[2] = signal->depth;

  Rgb_Color color;
  Set_Color(&color, 255, 0, 0);

  int seed_offset = -1;

  double z_scale = 1.0;

  if (Is_Arg_Matched("-res")) {
    if (fexist(Get_String_Arg("-res"))) {
      double res[3];
      int length;
      darray_read2(Get_String_Arg("-res"), res, &length);
      if (res[0] != res[1]) {
	perror("Different X-Y resolutions.");
	TZ_ERROR(ERROR_DATA_VALUE);
      }
      z_scale = res[0] / res[2] * 2.0;
    }
  }
  
  if (Is_Arg_Matched("-z")) {
    z_scale = Get_Double_Arg("-z");
  }

  printf("z scale: %g\n", z_scale);

  tic();


  double *values = darray_malloc(seed->size);

  int i;
  Local_Neuroseg *locseg = (Local_Neuroseg *) 
    malloc(seed->size * sizeof(Local_Neuroseg));


  int index = 0;

  //int ncol = LOCAL_NEUROSEG_NPARAM + 1 + 23;
  //double *features = darray_malloc(seed->size * ncol);
  //double *tmpfeats = features;

  Stack *seed_mask = Make_Stack(GREY, signal->width, signal->height, 
				signal->depth);
  Zero_Stack(seed_mask);

  Locseg_Fit_Workspace *fws = New_Locseg_Fit_Workspace();
  
  if (Is_Arg_Matched("-field")) {
    fws->sws->field_func = Neuroseg_Slice_Field_Func(Get_Int_Arg("-field"));
  }

  fws->sws->fs.n = 2;
  fws->sws->fs.options[0] = STACK_FIT_DOT;
  fws->sws->fs.options[1] = STACK_FIT_CORRCOEF;

  if (Is_Arg_Matched("-fo")) {
    fws->sws->fs.options[1] = Get_Int_Arg("-fo");
  }

  for (i = 0; i < seed->size; i++) {
    printf("-----------------------------> seed: %d / %d\n", i, seed->size);

    index = i;
    int x = (int) seed->points[index][0];
    int y = (int) seed->points[index][1];
    int z = (int) seed->points[index][2];

    double width = seed->values[index];

    seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height,
				    signal->depth);

    if (width < 3.0) {
      width += 0.5;
    }
    Set_Neuroseg(&(locseg[i].seg), width, 0.0, NEUROSEG_DEFAULT_H, 
		 0.0, 0.0, 0.0, 0.0, 1.0);

    double cpos[3];
    cpos[0] = x;
    cpos[1] = y;
    cpos[2] = z;
    cpos[2] /= z_scale;
    
    Set_Neuroseg_Position(&(locseg[i]), cpos, NEUROSEG_CENTER);

    if (seed_mask->array[seed_offset] > 0) {
      printf("labeled\n");
      values[i] = 0.0;
      continue;
    }

    //Local_Neuroseg_Optimize(locseg + i, signal, z_scale, 0);
    Local_Neuroseg_Optimize_W(locseg + i, signal, z_scale, 0, fws);

    values[i] = fws->sws->fs.scores[1];
    /*
    Stack_Fit_Score fs;
    fs.n = 1;
    fs.options[0] = 1;
    values[i] = Local_Neuroseg_Score(locseg + i, signal, z_scale, &fs);
    */

    //values[i] = Local_Neuroseg_Score_W(locseg + i, signal, z_scale, sws);

    printf("%g\n", values[i]);

    double min_score = LOCAL_NEUROSEG_MIN_CORRCOEF;
    if (Is_Arg_Matched("-min_score")) {
      min_score = Get_Double_Arg("-min_score");
    }

    if (values[i] > min_score) {
      Local_Neuroseg_Label_G(locseg + i, seed_mask, -1, 2, z_scale);
    } else {
      Local_Neuroseg_Label_G(locseg + i, seed_mask, -1, 1, z_scale);
    }

    /*
    tmpfeats += Local_Neuroseg_Param_Array(locseg + i, z_scale, tmpfeats);
    
    tmpfeats += Local_Neuroseg_Stack_Feature(locseg + i, signal, z_scale, 
					     tmpfeats); 
    */
  }

  if (Is_Arg_Matched("-e")) {
    Write_Stack(Get_String_Arg("-e"), seed_mask);
  }
  Write_Local_Neuroseg_Array(Get_String_Arg("-o"), locseg, seed->size);

  char file_path[MAX_PATH_LENGTH];
  sprintf(file_path, "%s_score", Get_String_Arg("-o"));
  darray_write(file_path, values, seed->size);

  //sprintf(file_path, "%s_feat", Get_String_Arg("-o"));
  //darray_write(file_path, features, seed->size * ncol); 

  Kill_Geo3d_Scalar_Field(seed);

  printf("Time passed: %lld\n", toc());

  
  return 0;
}
Пример #10
0
void
x11_fplot(const XDpy * dpy, XAnim * anim, XFall * fall,
	color_t * pal, uint pal_len,
	int x, int y, uint w, uint h,
	double *xdat, double *ydat, uint l,
	double samp_rate,
	const char *xtitle, const char *ytitle,
	const char *fx_title, const char *fy_title,
	int is_log,
	box2d * taxx, box2d * faxx, uint axxhint)
{
  int x1, y1, w1, h1;
  int x2, y2, w2, h2;
  int x3, y3, w3, h3;

  w1 = w;
  w2 = w;
  w3 = w;

  h1 = h / 3;
  h2 = h / 3;
  h3 = h - h1 - h2;

  x1 = x;
  x2 = x;
  x3 = x;

  y1 = y;
  y2 = y + h1;
  y3 = y + 2 * h1;

  if (taxx) {
    double xmin, xmax;
    double ymin, ymax;

    /* get extremes and spans */
    darray_extremes(xdat, l, &xmin, &xmax);
    darray_extremes(ydat, l, &ymin, &ymax);

    if (axxhint == 0) {
      box2d_set(taxx, xmin, ymin, xmax, ymax);
    } else {
      /* extend it */
      taxx->l.x = MIN2(taxx->l.x, xmin);
      taxx->l.y = MIN2(taxx->l.y, ymin);
      taxx->u.x = MAX2(taxx->u.x, xmax);
      taxx->u.y = MAX2(taxx->u.y, ymax);
    }

    x11_plot(dpy, anim, x1, y1, w1, h1, xdat, ydat, l,
	   taxx->l.x, taxx->u.x,
	   taxx->l.y, taxx->u.y,
	   xtitle, ytitle);
  } else {
    x11_plot_autoaxis(dpy, anim, x1, y1, w1, h1, xdat, ydat, l,
		    xtitle, ytitle);
  }

  double *xi = darray_calloc(l);	/* zeros */
  double *tre = darray_malloc(l);	/* real part of time domain data */
  double *tim = darray_malloc(l);	/* imag part of time domain data */
  double *abs = darray_malloc(l);

  uint lo2 = l / 2;
  double *fscale = darray_malloc(lo2);
  darray_ramp(fscale, lo2, 0, samp_rate / 2 / lo2);

  double *ydat_f = darray_malloc(l);

  uint i;

  /* windowing filter */
  for (i = 0; i < l; i++) {
    ydat_f[i] = ydat[i] * double_blackman(i, l);
  }

  if (IS_BINPOW(l)) {		/* only if length is a power of two */
    /* can we perform an FFT */
    darray_FFT(tre, tim, ydat_f, xi, l);
    darray_eud2D(abs, tre, tim, l);
    if (is_log) {
      uint i;
      for (i = 0; i < l; i++) {
	abs[i] = log10(abs[i]);
      }
    }

    if (faxx) {
      double xmin, xmax;
      double ymin, ymax;

      /* get extremes and spans */
      darray_extremes(fscale, lo2, &xmin, &xmax);
      darray_extremes(abs, l, &ymin, &ymax);

      if (axxhint == 0) {
	box2d_set(faxx, xmin, ymin, xmax, ymax);
      } else {
	/* extend it */
	faxx->l.x = MIN2(faxx->l.x, xmin);
	faxx->l.y = MIN2(faxx->l.y, ymin);
	faxx->u.x = MAX2(faxx->u.x, xmax);
	faxx->u.y = MAX2(faxx->u.y, ymax);
      }

      x11_plot(dpy, anim,
	     x2, y2, w2, h2, fscale, abs, lo2,
	     faxx->l.x, faxx->u.x,
	     faxx->l.y, faxx->u.y,
	     fx_title, fy_title);
    } else {
      x11_plot_autoaxis(dpy, anim,
		      x2, y2, w2, h2, fscale, abs, lo2,
		      fx_title, fy_title);
    }

    double ymin, ymax;
    darray_extremes(abs, l, &ymin, &ymax);
    double yspan = ymax - ymin;
    color_t * cols = (color_t*)malloc(lo2 * sizeof(color_t));
    /* Waterfall */
    for (i = 0; i < lo2; i++) {
      uint val =
	uint_clamp(0,
		   (uint)((abs[i] - ymin) / yspan * (pal_len - 1)),
		   pal_len - 1);
      cols[i] = pal[val];
    }
    x11_appFall(dpy, anim, fall, cols, lo2);
    free(cols);
    x11_dWFall(dpy, anim, fall, x3, y3);

  } else {
    leprintf("%s: n=%u is not a power of two. Returning.\n", __FUNCTION__, l);
  }

  free(xi);
  free(tre);
  free(tim);
  free(abs);
  free(fscale);
  free(ydat_f);
}
Пример #11
0
/*
 * trace_neuron - trace neuron from given seeds
 *
 * trace_neuron [!wtr] seed_file -Dsave_dir
 *   -r: write intermediate results
 *
 */
int main(int argc, char* argv[])
{
  static char *Spec[] = {
    "[!wtr] [-canvas <string>] [-mask <string>] [-res <string>] [-minr <int>]",
    "-minlen <double>",
    " <image:string> -S<string> -D<string>",
    NULL};
  
  Process_Arguments(argc, argv, Spec, 1);
  
  char *dir = Get_String_Arg("-D");
  
  char file_path[100];
  sprintf(file_path, "%s/%s", dir, Get_String_Arg("-S"));
  printf("%s\n", file_path);

  Geo3d_Scalar_Field *seed = Read_Geo3d_Scalar_Field(file_path);

  int idx;

  sprintf(file_path, "%s/%s.bn", dir, "max_r");
  double max_r;
  int tmp;
  if (fexist(file_path)) {
    darray_read2(file_path, &max_r, &tmp);
  } else {
    max_r = darray_max(seed->values, seed->size, &idx);
  }

  printf("%g\n", max_r);

  max_r *= 1.5;

  /*
  sprintf(file_path, "%s/%s", dir, "soma0.bn");
  if (!fexist(file_path)) {
    max_r *= 2.0;
  }
  */
   
  Set_Neuroseg_Max_Radius(max_r);

  Stack *signal = Read_Stack(Get_String_Arg("image"));

  dim_type dim[3];
  dim[0] = signal->width;
  dim[1] = signal->height;
  dim[2] = signal->depth;
  /* 
  IMatrix *chord = Make_IMatrix(dim, 3);
  
  Stack *code = Make_Stack(GREY16, 
			   signal->width, signal->height, signal->depth);
  */
  Rgb_Color color;
  Set_Color(&color, 255, 0, 0);

  Stack *canvas = NULL;

  char trace_file_path[100];
  sprintf(trace_file_path, "%s/%s", dir, Get_String_Arg("-canvas"));
  
  if (fexist(trace_file_path) == 1) {
    canvas = Read_Stack((char *) trace_file_path);
  } else {
    canvas = Copy_Stack(signal);
    Stretch_Stack_Value_Q(canvas, 0.999);
    Translate_Stack(canvas, COLOR, 1);
  }

  Stack *traced = NULL;
  
  char trace_mask_path[100];
  sprintf(trace_mask_path, "%s/%s", dir, Get_String_Arg("-mask"));

  if (fexist(trace_mask_path) == 1) {
    traced = Read_Stack((char *) trace_mask_path);
  } else {
    traced = Make_Stack(GREY, signal->width, signal->height, signal->depth);
    One_Stack(traced);
  }
  

  //Object_3d *obj = NULL;
  int seed_offset = -1;

  Neurochain *chain = NULL;

  double z_scale = 1.0;

  if (Is_Arg_Matched("-res")) {
    sprintf(file_path, "%s", Get_String_Arg("-res"));

    if (fexist(file_path)) {
      double res[3];
      int length;
      darray_read2(file_path, res, &length);
      if (res[0] != res[1]) {
	perror("Different X-Y resolutions.");
	TZ_ERROR(ERROR_DATA_VALUE);
      }
      z_scale = res[0] / res[2];
    }
  }

  //sprintf(file_path, "%s/%s", dir, Get_String_Arg("-M"));
  //Stack *stack = Read_Stack(file_path);

  tic();

  FILE *fp = NULL;
  char chain_file_path[100];
  char vrml_file_path[100];

  double min_chain_length = 25.0;

  if (Is_Arg_Matched("-minlen")) {
    min_chain_length = Get_Double_Arg("-minlen");
  }

  int *indices = iarray_malloc(seed->size);
  double *values = darray_malloc(seed->size);
  int i;

  Local_Neuroseg *locseg = (Local_Neuroseg *) 
    malloc(seed->size * sizeof(Local_Neuroseg));

  int index = 0;
  for (i = 0; i < seed->size; i++) {
    printf("-----------------------------> seed: %d / %d\n", i, seed->size);
    indices[i] = i;
    index = i;
    int x = (int) seed->points[index][0];
    int y = (int) seed->points[index][1];
    int z = (int) seed->points[index][2];

    double width = seed->values[index];

    chain = New_Neurochain();

    seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height,
				    signal->depth);

    if (width < 3.0) {
      width += 0.5;
    }
    Set_Neuroseg(&(locseg[i].seg), width, width, 12.0, 
		 0.0, 0.0, 0.0);

    double cpos[3];
    cpos[0] = x;
    cpos[1] = y;
    cpos[2] = z;
    cpos[2] *= z_scale;
    
    Set_Neuroseg_Position(&(locseg[i]), cpos, NEUROSEG_CENTER);
    Stack_Fit_Score fs;
    fs.n = 1;
    fs.options[0] = 1;
    values[i] = Local_Neuroseg_Orientation_Search_C(&(locseg[i]), signal, z_scale, &fs);
  }

  darray_qsort(values, indices, seed->size);

  /*
  for (i = 0; i < seed->size; i++) {
    indices[i] = i;
  }
  darraycpy(values, seed->values, 0, seed->size);
  darray_qsort(values, indices, seed->size);
  */

  int counter = 0;

  //  for (i = seed->size - 1; i >= seed->size - 231; i--) {
  for (i = seed->size - 1; i >= 0; i--) {
    index = indices[i];

    printf("-----------------------------> seed: %d / %d\n", i, seed->size);
    
    sprintf(chain_file_path, "%s/chain%d.bn", dir, index);
    sprintf(vrml_file_path, "%s/chain%d.wrl", dir, index);

    if (fexist(chain_file_path) == 1) {
      chain = Read_Neurochain(chain_file_path);
      if (Neurochain_Geolen(chain) >= min_chain_length) {
	Write_Neurochain_Vrml(vrml_file_path, chain);
	Neurochain_Label(canvas, chain, z_scale);
	Neurochain_Erase_E(traced, chain, z_scale, 0,
			   Neurochain_Length(chain, FORWARD),
			   1.5, 0.0);
      }

      Free_Neurochain(chain);
      printf("chain exists\n");
      continue;
    }
    
    
    int x = (int) seed->points[index][0];
    int y = (int) seed->points[index][1];
    int z = (int) seed->points[index][2];

    if (*STACK_PIXEL_8(traced, x, y, z, 0) == 0) {
      printf("traced \n");
      continue;
    }

    double width = seed->values[index];

    if (width > max_r) {
      printf("too thick\n");
      continue;
    }
    
    if (Is_Arg_Matched("-minr")) {
      int max_level = (int) (width + 0.5);
      if (max_level <= Get_Int_Arg("-minr")) {
	printf("too thin\n");
	continue;
      }
    }
    /*
    seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height,
				    signal->depth);
    */

    chain = New_Neurochain();
    /*
    Stack_Level_Code_Constraint(stack, code, chord->array, &seed_offset, 1, 
				max_level + 1);

    Voxel_t v;
    v[0] = x;
    v[1] = y;
    v[2] = z;

    Stack *tmp_stack = Copy_Stack(stack);
    obj = Stack_Grow_Object_Constraint(tmp_stack, 1, v, chord, code, 
				       max_level);
    Free_Stack(tmp_stack);

    Print_Object_3d_Info(obj);
    
    double vec[3];
    Object_3d_Orientation_Zscale(obj, vec, MAJOR_AXIS, z_scale);

    double theta, psi;
    Geo3d_Vector obj_vec;
    Set_Geo3d_Vector(&obj_vec, vec[0], vec[1], vec[2]);

    Geo3d_Vector_Orientation(&obj_vec, &theta, &psi);
    */

    /*
    if (width < 3.0) {
      width += 0.5;
    }
    Set_Neuroseg(&(chain->locseg.seg), width, width, 12.0, 
		 0.0, 0.0, 0.0);

    double cpos[3];
    cpos[0] = x;
    cpos[1] = y;
    cpos[2] = z;
    cpos[2] *= z_scale;
    
    //Set_Neuroseg_Position(&(chain->locseg), cpos, NEUROSEG_BOTTOM);
    Set_Neuroseg_Position(&(chain->locseg), cpos, NEUROSEG_CENTER);
    Stack_Fit_Score fs;
    fs.n = 1;
    fs.options[0] = 1;
    Local_Neuroseg_Orientation_Search_C(&(chain->locseg), signal, z_scale,
					&fs); 
    //fs.options[0] = 1;
    */

    Copy_Local_Neuroseg(&(chain->locseg), &(locseg[index]));
    Neurochain *chain_head = chain;
    
    
    if (Initialize_Tracing(signal, chain, NULL, z_scale) >= MIN_SCORE) {
      if ((Neuroseg_Hit_Traced(&(chain->locseg), traced, z_scale) == FALSE) &&
	  (chain->locseg.seg.r1 < max_r) && 
	  (chain->locseg.seg.r2 < max_r)) {
	//Initialize_Tracing(signal, chain, NULL, z_scale);
	chain = Trace_Neuron2(signal, chain, BOTH, traced, z_scale, 500);

	//Neurochain *chain_head = Neurochain_Head(chain);
	chain_head = Neurochain_Remove_Overlap_Segs(chain);
	chain_head = Neurochain_Remove_Turn_Ends(chain_head, 0.5);
	/*
	if (i == seed->size - 231) {
	  Print_Neurochain(chain_head);
	}
	*/

	fp = fopen(chain_file_path, "w");
	Neurochain_Fwrite(chain_head, fp);
	fclose(fp);
	if (Neurochain_Geolen(chain_head) >= min_chain_length) {
	  Write_Neurochain_Vrml(vrml_file_path, chain_head);

	  Neurochain_Erase_E(traced, chain_head, z_scale, 0,
			     Neurochain_Length(chain_head, FORWARD),
			     1.5, 0.0);
	  Neurochain_Label(canvas, chain_head, z_scale);

	  counter += Neurochain_Length(chain_head, FORWARD);
	  if (counter > 500) {
	    if (Is_Arg_Matched("-r")) {
	      Write_Stack((char *) trace_mask_path, traced);
	    }
	    
	    if (Is_Arg_Matched("-r")) {
	    Write_Stack((char *) trace_file_path, canvas);
	    }

	    counter = 0;
	  }
	}
      }
    }

    Free_Neurochain(chain_head);

    //Kill_Object_3d(obj);
  }

  Write_Stack((char *) trace_file_path, canvas);
  if (Is_Arg_Matched("-r")) {
    Write_Stack((char *) trace_mask_path, traced);
  }

  Kill_Geo3d_Scalar_Field(seed);

  printf("Time passed: %lld\n", toc());

  
  return 0;
}