Exemplo n.º 1
0
/**
 * We need to report error in idle moment
 * since we can't report_error before gtk_main is called.
 * This function is attached via g_idle_add() in init_libnotify().
 *
 * @param data passed to the function,
 * set when the source was created
 * @return FALSE if the source should be removed,
 * TRUE otherwise
 */
static gboolean idle_report_error(gpointer data) {
  report_error("Unable to initialize libnotify.  Notifications will not be sent");
  return FALSE;
}
static void print_kmer_stats()
{
  char num_str[50];

  if(num_of_all_zero_kmers > 1)
  {
    report_error("%s all-zero-kmers seen\n",
                 ulong_to_str(num_of_all_zero_kmers, num_str));
  }

  if(num_of_oversized_kmers > 0)
  {
    report_error("%s oversized kmers seen\n",
                 ulong_to_str(num_of_oversized_kmers, num_str));
  }

  if(num_of_zero_covg_kmers > 0)
  {
    report_warning("%s kmers have no coverage in any colour\n",
                   ulong_to_str(num_of_zero_covg_kmers, num_str));
  }

  if((print_kmers || parse_kmers) && print_info)
  {
    printf("kmers read: %s\n", ulong_to_str(num_of_kmers_read, num_str));
    printf("covgs read: %s\n", ulong_to_str(sum_of_covgs_read, num_str));
    printf("seq loaded: %s\n", ulong_to_str(sum_of_seq_loaded, num_str));
  }

  if(print_info)
  {
    // Memory calculations
    // use expected number of kmers if we haven't read the whole file
    unsigned long kmer_count
      = (print_kmers || parse_kmers ? num_of_kmers_read : expected_num_of_kmers);

    // Number of hash table entries is 2^mem_height * mem_width
    // Aim for 80% occupancy once loaded
    float extra_space = 10.0/8;
    unsigned long hash_capacity = extra_space * kmer_count;

    // mem_width must be within these boundaries
    unsigned int min_mem_width = 5;
    unsigned int max_mem_width = 50;
    unsigned int min_mem_height = 12;
    // min mem usage = 2^12 * 5 = 20,480 entries = 320.0 KB with k=31,cols=1

    unsigned long mem_height = min_mem_height;
    unsigned long mem_width = max_mem_width;
    unsigned long hash_entries = (0x1UL << mem_height) * mem_width;

    if(hash_capacity > hash_entries)
    {
      // Resize
      mem_height = Log2((double)hash_capacity / (max_mem_width-1))+0.99;
      mem_height = MIN2(mem_height, 32);
      mem_height = MAX2(mem_height, min_mem_height);

      mem_width = hash_capacity / (0x1UL << mem_height) + 1;

      printf("mem_width: %lu; mem_height: %lu;\n", mem_width, mem_height);

      if(mem_width < min_mem_width)
      {
        // re-calculate mem_height
        mem_height = Log2((double)hash_capacity / min_mem_width)+0.99;
        mem_height = MIN2(mem_height, 32);
        mem_height = MAX2(mem_height, min_mem_height);
        mem_width = hash_capacity / (0x1UL << mem_height) + 1;
        mem_width = MAX2(mem_width, min_mem_width);
      }

      hash_entries = (0x1UL << mem_height) * mem_width;
    }

    char min_mem_required[50];
    char rec_mem_required[50];

    set_memory_required_str(kmer_count, min_mem_required);
    set_memory_required_str(hash_entries, rec_mem_required);

    printf("Memory required: %s\n", min_mem_required);
    printf("Memory suggested: --mem_width %lu --mem_height %lu\n",
           mem_width, mem_height);

    char hash_entries_numstr[50];
    ulong_to_str(hash_entries, hash_entries_numstr);

    printf("  [%s entries; %s memory]\n", hash_entries_numstr, rec_mem_required);
  }
}
Exemplo n.º 3
0
main()
{
   int                  sts, i, zro=0;
   OM_S_OBJID           a_objid[MAXA], b_objid[MAXB], c_objid;
   OM_S_OBJID           resa_objid[MAXA], resb_objid[MAXB], c2_objid;
   OM_S_CHANNUM         chan_a, chan_b;
   OM_S_CHANNUM         chan_resa, chan_resb;
   uword                count, siz;
   char                 *chan_acany,*chan_acbc,*chan_acb,*chan_bca;
   char                 *chan_sbca;
   char                 *chan_resacany,*chan_resacbc,*chan_resacb,*chan_resbca;
   char                 *chan_sca;
   OM_S_CHANSELECT      chansel;
   int		        relindex=0, to=0, from=0;
   OM_S_MESSAGE 	showb,showresb,connect_msg,move_chan_msg;
   uword        	OSnum;
   uword	        minorchan=0;
   
struct connect_struct
       {
	 OM_S_CHANSELECT      to_sel;
	 int		      to_idx;
	 OM_S_OBJID	      fr_objid;
	 uword                fr_os;
	 OM_S_CHANSELECT      fr_sel;
	 int		      fr_idx;
       } connect_args;
struct move_chan_struct
       {
	 OM_S_CHANSELECT      to_sel;
	 OM_S_OBJID	      fr_objid;
	 OMuword              fr_os;
	 OM_S_CHANSELECT      fr_sel;
       } move_chan_args;
   sts = om$runtime_init();
   if (!(sts&1))
   {
      printf (" error in om%runtine_init\n" );
      om$report_error(sts = sts);
      exit();
   }

   OSnum = OM_Gw_TransOSnum_0;
   

   chan_acb  = "A.acb";
   chan_acany  = "A.acany";
   chan_acbc = "A.acbc";
   chan_bca  = "B.bca";
   chan_sbca  = "C.sbca";

   for ( i=0; i<MAXA; i++ )
   {
      sts = om$construct(osname = "OM_TransOS_0",
                         classname = "A",
                         p_objid = &a_objid[i],
                         neighbor = OM_GS_NULL_NEIGHBOR);
      if (!(sts&1))
      {
         printf (" error in om$construct for A\n" );
         om$report_error(sts = sts);
         printf (" iteration : %d \n", i );
         exit();
      }
   }


   sts = om$get_channel_number(channame = "A.acb",
                               p_channum = &chan_a );
   if (!(sts&1))
   {
      printf (" error in om$get channel_number for acb\n" );
      om$report_error(sts = sts);
      exit();
   }

   sts = om$get_channel_number(channame = "B.bca",
                               p_channum = &chan_b );
   if (!(sts&1))
   {
      printf (" error in om$get_channel_number for bca\n" );
      om$report_error(sts = sts);
      exit();
   }


   for ( i=0; i<MAXB; i++ )
   {
      sts = om$construct(osname = "OM_TransOS_0",
                         classname = "B",
                         p_objid = &b_objid[i],
                         neighbor = OM_GS_NULL_NEIGHBOR);
      if (!(sts&1))
      {
         printf (" error in om$construct for B\n" );
         om$report_error(sts = sts);
         printf (" iteration : %d \n", i );
         exit();
      }
   } /* for */

/* Now I need to build the following relations for the test:
	a1 - b0    	Dipole
	a2,a3 - b1  	TO:FROM
	a4 - b2,b3	FROM:TO
	a5 - b4         Dipole
	a10 - b5	Dipole
*/

	connect_args.to_sel.type = OM_e_num;
	connect_args.to_sel.u_sel.number = chan_b;
	connect_args.to_idx = 0;
	connect_args.fr_objid = a_objid[1];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_num;
	connect_args.fr_sel.u_sel.number = chan_a;
	connect_args.fr_idx            = 0;

	sts = om$make_message(classname = "Root",		
			      methodname = "connect",		
			      size = sizeof( struct connect_struct),
			      p_arglist = &connect_args,	
			      p_msg = &connect_msg );


	sts = om$send (msg = &connect_msg,			
		       senderid = a_objid[1],			
		       targetid = b_objid[0] );

   if (!(sts&1))
      {
      printf (" error in om$send (connect) for B\n" );
      om$report_error(sts = sts);
      exit();
      }
   printf ("A1 connected to B0\n");

   printf ("----- Dumping A[1]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[1], "acb" );

   printf ("----- Dumping B[0]'s bca channel\n");
   OMT_dump_relation( OM_Gw_current_OS, b_objid[0], "bca" );
   
     
for(i=2; i<4; i++)
{
	connect_args.to_sel.type = OM_e_name;
	connect_args.to_sel.u_sel.name = chan_bca;
	connect_args.to_idx = 0;
	connect_args.fr_objid = a_objid[i];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_name;
	connect_args.fr_sel.u_sel.name = chan_acb;
	connect_args.fr_idx            = 0;

	sts = om$send (msg = &connect_msg,			
		       senderid = a_objid[i],			
		       targetid = b_objid[1] );
 
   switch(sts)
   {
      case OM_I_ADDEDATEND:
      case OM_S_SUCCESS:  printf("A%d connected to B1\n", i);
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("B1 is already connected\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (connect) for A%d to B1\n", i);
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[%d]'s acb channel\n",i);
   OMT_dump_relation( OM_Gw_current_OS, a_objid[i], "acb" );

   printf ("----- Dumping B[1]'s bca channel\n");
   OMT_dump_relation( OM_Gw_current_OS, b_objid[1], "bca" );
}
      

for(i=2; i<4; i++)
{
	connect_args.to_sel.type = OM_e_name;
	connect_args.to_sel.u_sel.name = chan_bca;
	connect_args.to_idx = 0;
	connect_args.fr_objid = a_objid[4];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_name;
	connect_args.fr_sel.u_sel.name = chan_acb;
	connect_args.fr_idx            = 0;

	sts = om$send (msg = &connect_msg,			
		       senderid = a_objid[4],			
		       targetid = b_objid[i] );

   switch(sts)
   {
      case OM_I_ADDEDATEND:
      case OM_S_SUCCESS:  printf("A4 connected to B%d\n", i);
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (connect) for A4 to B%d\n", i);
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[4]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[4], "acb" );

   printf ("----- Dumping B[%d]'s bca channel\n",i);
   OMT_dump_relation( OM_Gw_current_OS, b_objid[i], "bca" );
}

	connect_args.to_sel.type = OM_e_name;
	connect_args.to_sel.u_sel.name = chan_bca;
	connect_args.to_idx = 0;
	connect_args.fr_objid = a_objid[5];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_name;
	connect_args.fr_sel.u_sel.name = chan_acb;
	connect_args.fr_idx            = 0;

	sts = om$send (msg = &connect_msg,			
		       senderid = a_objid[5],			
		       targetid = b_objid[4] );
 
   if (!(sts&1))
      {
      printf (" error in om$send (connect)\n");
      om$report_error(sts = sts);
      exit();
      }
   printf ("A5 connected to B4\n");

   printf ("----- Dumping A[5]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[5], "acb" );

   printf ("----- Dumping B[4]'s bca channel\n");
   OMT_dump_relation( OM_Gw_current_OS, b_objid[4], "bca" );

	connect_args.to_sel.type = OM_e_name;
	connect_args.to_sel.u_sel.name = chan_bca;
	connect_args.to_idx = 0;
	connect_args.fr_objid = a_objid[10];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_name;
	connect_args.fr_sel.u_sel.name = chan_acb;
	connect_args.fr_idx            = 0;

	sts = om$send (msg = &connect_msg,			
		       senderid = a_objid[10],			
		       targetid = b_objid[5] );
   if (!(sts&1))
      {
      printf (" error in om$send (connect)\n");
      om$report_error(sts = sts);
      exit();
      }

   printf ("A10 connected to B5\n");

   printf ("----- Dumping A[10]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[10], "acb" );

   printf ("----- Dumping B[5]'s bca channel\n");
   OMT_dump_relation( OM_Gw_current_OS, b_objid[5], "bca" );

/******************************************************************
Test # 1 - Source is a singleton.
*******************************************************************/

   printf ("\n\n******* Test 1 - A0.acb to A6.acb but A0 is empty\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_acb;
	move_chan_args.fr_objid = a_objid[0];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_acb;

	sts = om$make_message(classname = "Root",		
			      methodname = "move_chan",		
			      size = sizeof( struct move_chan_struct),
			      p_arglist = &move_chan_args,	
			      p_msg = &move_chan_msg );

	sts = om$send (msg = &move_chan_msg,			
		       senderid = a_objid[0],			
		       targetid = a_objid[6] );

   switch(sts)
   {
      case OM_I_CHAN_EMPTY:
      case OM_S_SUCCESS:  printf("\n\nA0.acb moved to A6.acb\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for A0 to A6\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[0]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[0], "acb" );

   printf ("----- Dumping A[6]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[6], "acb" );


/******************************************************************
Test # 2 - Source is a dipole.
*******************************************************************/

   printf ("\n\n******* Test 2 - A1.acb to A7.acb\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_acb;
	move_chan_args.fr_objid = a_objid[1];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_acb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = a_objid[1],			
		       targetid = a_objid[7] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nA1.acb moved to A7.acb\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for A1 to A7\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[1]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[1], "acb" );

   printf ("----- Dumping A[7]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[7], "acb" );

   sts = om$make_message(classname = "B",
                         methodname = "show_b",
                         size = 0,
                         p_arglist = 0,
                         p_msg = &showb);
   if(!(sts&1))
   {
	printf("error in om%make_message for show_b\n");
	om$report_error(sts = sts);
	exit();
   }
   chansel.type = OM_e_name;
   chansel.u_sel.name = chan_acb;
   sts = om$send(mode = OM_e_wrt_object,
                 msg = &showb,
                 senderid = a_objid[7],
                 p_chanselect = &chansel);
   if(!(sts&1))
   {
	printf("error in om$send (show_b)\n");
	om$report_error(sts = sts);
	exit();
   }

/******************************************************************
Test # 3 - Source is on the TO side of a relation.
*******************************************************************/

   printf ("\n\n******* Test 3 - A2.acb to A8.acb\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_acb;
	move_chan_args.fr_objid = a_objid[2];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_acb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = a_objid[2],			
		       targetid = a_objid[8] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nA2.acb moved to A8.acb\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for A2 to A8\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[2]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[2], "acb" );

   printf ("----- Dumping A[8]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[8], "acb" );

   chansel.type = OM_e_name;
   chansel.u_sel.name = chan_acb;
   sts = om$send(mode = OM_e_wrt_object,
                 msg = &showb,
                 senderid = a_objid[8],
                 p_chanselect = &chansel);
   if(!(sts&1))
   {
	printf("error in om$send (show_b)\n");
	om$report_error(sts = sts);
	exit();
   }

/******************************************************************
Test # 4 - Source is on the FROM side of a relation.
*******************************************************************/

   printf ("\n\n******* Test 4 - A4.acb to A9.acb\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_acb;
	move_chan_args.fr_objid = a_objid[4];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_acb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = a_objid[4],			
		       targetid = a_objid[9] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nA4.acb moved to A9.acb\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for A4 to A9\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[4]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[4], "acb" );

   printf ("----- Dumping A[9]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[9], "acb" );

   chansel.type = OM_e_name;
   chansel.u_sel.name = chan_acb;
   sts = om$send(mode = OM_e_wrt_object,
                 msg = &showb,
                 senderid = a_objid[9],
                 p_chanselect = &chansel);
   if(!(sts&1))
   {
	printf("error in om$send (show_b)\n");
	om$report_error(sts = sts);
	exit();
   }

/******************************************************************
Test # 5 - Source is a dipole and target is a dipole.  This should 
           generate a error because the target should be empty.
*******************************************************************/

   printf ("\n\n******* Test 5 - A5.acb to A10.acb but A10.acb is not empty\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_acb;
	move_chan_args.fr_objid = a_objid[5];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_acb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = a_objid[5],			
		       targetid = a_objid[10] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nA5.acb moved to A10\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("\nOM_E_INVCHAN - expected error\n\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for A5 to A10\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[5]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[5], "acb" );

   printf ("----- Dumping A[10]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[10], "acb" );

/******************************************************************
Test # 6 - Source is a dipole and its channel has only Bs on rhs.  
           Target is empty and its channel accepts Bs & Cs on rhs.
	   Target channel is a superset of Source's channel.
*******************************************************************/

   printf ("\n\n******* Test 6 - A7.acb to A1.acbc\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_acbc;
	move_chan_args.fr_objid = a_objid[7];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_acb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = a_objid[7],			
		       targetid = a_objid[1] );

   switch(sts)
   {
      case OM_I_CHAN_EMPTY:
      case OM_S_SUCCESS:  printf("\n\nA7.acb moved to A1.acbc\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for A7.acb to A1.acbc\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[7]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[7], "acb" );

   printf ("----- Dumping A[1]'s acbc channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[1], "acbc" );

/******************************************************************
Test # 7 - Source is FROM side of relation and its channel has
		 only Bs on rhs.  
           Target is empty and its channel accepts any class on rhs.
	   Target channel is a wildcard channel.
*******************************************************************/

   printf ("\n\n******* Test 7 - A9.acb to A10.acany\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_acany;
	move_chan_args.fr_objid = a_objid[9];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_acb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = a_objid[9],			
		       targetid = a_objid[10] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nA9.acb moved to A10.acany\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for A9.acb to A10.acany\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[9]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[9], "acb" );

   printf ("----- Dumping A[10]'s acany channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[10], "acany" );

/******************************************************************
Test # 8 - Source is FROM side of relation and its channel has
	    only any class on rhs.  
           Target is empty and its channel accepts Bs & Cs on rhs.
	   Target channel is a subset of source channel but all
	    objects currently hooked to channel are allowed on source.
*******************************************************************/

   printf ("\n\n******* Test 8 - A10.acany to A4.acbc\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_acbc;
	move_chan_args.fr_objid = a_objid[10];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_acany;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = a_objid[10],			
		       targetid = a_objid[4] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nA10.acany moved to A4.acbc\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for A10.acany to A4.acbc\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[10]'s acany channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[10], "acany" );

   printf ("----- Dumping A[4]'s acbc channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[4], "acbc" );

/* Construct a C object and connect it to A[4].acbc */

      sts = om$construct(osname = "OM_TransOS_0",
                         classname = "C",
                         p_objid = &c_objid,
                         neighbor = OM_GS_NULL_NEIGHBOR);
      if (!(sts&1))
      {
         printf (" error in om$construct for C\n" );
         om$report_error(sts = sts);
         exit();
      }

	connect_args.to_sel.type = OM_e_name;
	connect_args.to_sel.u_sel.name = chan_sbca;
	connect_args.to_idx = 0;
	connect_args.fr_objid = a_objid[4];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_name;
	connect_args.fr_sel.u_sel.name = chan_acbc;
	connect_args.fr_idx            = 0;

	sts = om$send (msg = &connect_msg,			
		       senderid = a_objid[4],			
		       targetid = c_objid );
 
   if (!(sts&1))
      {
      printf (" error in om$send (connect) for C\n");
      om$report_error(sts = sts);
      exit();
      }

   printf ("A4 connected to C\n");

   printf ("----- Dumping A[4]'s acbc channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[4], "acbc" );

   printf ("----- Dumping C's sbca channel\n");
   OMT_dump_relation( OM_Gw_current_OS, c_objid, "sbca" );
   

/******************************************************************
Test # 9 - Source is FROM side of relation and its channel has
	    Bs and Cs on rhs.  
           Target is empty and its channel accepts only Bs on rhs.
	   Target channel is a subset of source channel but all
	    objects currently hooked to channel are not allowed
	    on source.  This test should fail.
*******************************************************************/

   printf ("\n\n******* Test 9 - A4.acbc to A9.acb but C is not allowed on acb\n");
	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_acb;
	move_chan_args.fr_objid = a_objid[4];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_acbc;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = a_objid[4],			
		       targetid = a_objid[9] );

   switch(sts)
   {
      case OM_I_CHAN_EMPTY:
      case OM_S_SUCCESS:  printf("\n\nA4.acbc moved to A9.acb\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_CLASS_CONFLICT: 
                         printf ("\nOM_E_CLASS_CONFLICT - expected error\n\n");
                         break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for A4.acbc to A9.acb\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping A[4]'s acbc channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[4], "acbc" );

   printf ("----- Dumping A[9]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, a_objid[9], "acb" );


   /*=========================================================*/
   /*=========================================================*/
   /*   R E S T R I C T E D     C H A N N E L    T E S T S    */
   /*=========================================================*/
   /*=========================================================*/

   printf ("\nStart of restrcited channel tests\n\n\n");

   chan_resacb    = "ResA.acb";
   chan_resacany  = "ResA.acany";
   chan_resacbc   = "ResA.acbc";
   chan_resbca    = "ResB.bca";
   chan_sca       = "C.sca";

   for ( i=0; i<MAXA; i++ )
   {
      sts = om$construct(osname = "OM_TransOS_0",
                         classname = "ResA",
                         p_objid = &resa_objid[i],
                         neighbor = OM_GS_NULL_NEIGHBOR);
      if (!(sts&1))
      {
         printf (" error in om$construct for ResA\n" );
         om$report_error(sts = sts);
         printf (" iteration : %d \n", i );
         exit();
      }
   }


   sts = om$get_channel_number(channame = "ResA.acb",
                               p_channum = &chan_a );
   if (!(sts&1))
   {
      printf (" error in om$get channel_number for acb\n" );
      om$report_error(sts = sts);
      exit();
   }

   sts = om$get_channel_number(channame = "ResB.bca",
                               p_channum = &chan_b );
   if (!(sts&1))
   {
      printf (" error in om$get_channel_number for bca\n" );
      om$report_error(sts = sts);
      exit();
   }


   for ( i=0; i<MAXB; i++ )
   {
      sts = om$construct(osname = "OM_TransOS_0",
                         classname = "ResB",
                         p_objid = &resb_objid[i],
                         neighbor = OM_GS_NULL_NEIGHBOR);
      if (!(sts&1))
      {
         printf (" error in om$construct for ResB\n" );
         om$report_error(sts = sts);
         printf (" iteration : %d \n", i );
         exit();
      }
   } /* for */

/* Now I need to build the following relations for the test:
	a1 - b0    	Dipole
	a2,a3 - b1  	TO:FROM
	a4 - b2,b3	FROM:TO
	a5 - b4         Dipole
	a10 - b5	Dipole
*/

	connect_args.to_sel.type = OM_e_num;
	connect_args.to_sel.u_sel.number = chan_b;
	connect_args.to_idx = 0;
	connect_args.fr_objid = resa_objid[1];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_num;
	connect_args.fr_sel.u_sel.number = chan_a;
	connect_args.fr_idx            = 0;

	sts = om$make_message(classname = "Root",		
			      methodname = "connect",		
			      size = sizeof( struct connect_struct),
			      p_arglist = &connect_args,	
			      p_msg = &connect_msg );


	sts = om$send (msg = &connect_msg,			
		       senderid = resa_objid[1],			
		       targetid = resb_objid[0] );

   if (!(sts&1))
      {
      printf (" error in om$send (connect) for ResB\n" );
      om$report_error(sts = sts);
      exit();
      }
   printf ("ResA1 connected to ResB0\n");

   printf ("----- Dumping ResA[1]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[1], "acb" );

   printf ("----- Dumping ResB[0]'s bca channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resb_objid[0], "bca" );
   
     
for(i=2; i<4; i++)
{
	connect_args.to_sel.type = OM_e_name;
	connect_args.to_sel.u_sel.name = chan_resbca;
	connect_args.to_idx = 0;
	connect_args.fr_objid = resa_objid[i];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_name;
	connect_args.fr_sel.u_sel.name = chan_resacb;
	connect_args.fr_idx            = 0;

	sts = om$send (msg = &connect_msg,			
		       senderid = resa_objid[i],			
		       targetid = resb_objid[1] );
 
   switch(sts)
   {
      case OM_I_ADDEDATEND:
      case OM_S_SUCCESS:  printf("ResA%d connected to ResB1\n", i);
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("ResB1 is already connected\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (connect) for ResA%d to ResB1\n", i);
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[%d]'s acb channel\n",i);
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[i], "acb" );

   printf ("----- Dumping ResB[1]'s bca channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resb_objid[1], "bca" );
}
      

for(i=2; i<4; i++)
{
	connect_args.to_sel.type = OM_e_name;
	connect_args.to_sel.u_sel.name = chan_resbca;
	connect_args.to_idx = 0;
	connect_args.fr_objid = resa_objid[4];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_name;
	connect_args.fr_sel.u_sel.name = chan_resacb;
	connect_args.fr_idx            = 0;

	sts = om$send (msg = &connect_msg,			
		       senderid = resa_objid[4],			
		       targetid = resb_objid[i] );

   switch(sts)
   {
      case OM_I_ADDEDATEND:
      case OM_S_SUCCESS:  printf("ResA4 connected to ResB%d\n", i);
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (connect) for ResA4 to ResB%d\n", i);
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[4]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[4], "acb" );

   printf ("----- Dumping ResB[%d]'s bca channel\n",i);
   OMT_dump_relation( OM_Gw_current_OS, resb_objid[i], "bca" );
}

	connect_args.to_sel.type = OM_e_name;
	connect_args.to_sel.u_sel.name = chan_resbca;
	connect_args.to_idx = 0;
	connect_args.fr_objid = resa_objid[5];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_name;
	connect_args.fr_sel.u_sel.name = chan_resacb;
	connect_args.fr_idx            = 0;

	sts = om$send (msg = &connect_msg,			
		       senderid = resa_objid[5],			
		       targetid = resb_objid[4] );
 
   if (!(sts&1))
      {
      printf (" error in om$send (connect)\n");
      om$report_error(sts = sts);
      exit();
      }
   printf ("ResA5 connected to ResB4\n");

   printf ("----- Dumping ResA[5]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[5], "acb" );

   printf ("----- Dumping ResB[4]'s bca channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resb_objid[4], "bca" );

	connect_args.to_sel.type = OM_e_name;
	connect_args.to_sel.u_sel.name = chan_resbca;
	connect_args.to_idx = 0;
	connect_args.fr_objid = resa_objid[10];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_name;
	connect_args.fr_sel.u_sel.name = chan_resacb;
	connect_args.fr_idx            = 0;

	sts = om$send (msg = &connect_msg,			
		       senderid = resa_objid[10],			
		       targetid = resb_objid[5] );
   if (!(sts&1))
      {
      printf (" error in om$send (connect)\n");
      om$report_error(sts = sts);
      exit();
      }

   printf ("ResA10 connected to ResB5\n");

   printf ("----- Dumping ResA[10]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[10], "acb" );

   printf ("----- Dumping ResB[5]'s bca channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resb_objid[5], "bca" );

/******************************************************************
Test # 1 - Source is a singleton.
*******************************************************************/

   printf ("\n\n******* Test 1 - ResA0.acb to ResA6.acb but ResA0 is empty\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_resacb;
	move_chan_args.fr_objid = resa_objid[0];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_resacb;

	sts = om$make_message(classname = "Root",		
			      methodname = "move_chan",		
			      size = sizeof( struct move_chan_struct),
			      p_arglist = &move_chan_args,	
			      p_msg = &move_chan_msg );

	sts = om$send (msg = &move_chan_msg,			
		       senderid = resa_objid[0],			
		       targetid = resa_objid[6] );

   switch(sts)
   {
      case OM_I_CHAN_EMPTY:
      case OM_S_SUCCESS:  printf("\n\nResA0.acb moved to ResA6.acb\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for ResA0 to ResA6\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[0]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[0], "acb" );

   printf ("----- Dumping ResA[6]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[6], "acb" );


/******************************************************************
Test # 2 - Source is a dipole.
*******************************************************************/

   printf ("\n\n******* Test 2 - ResA1.acb to ResA7.acb\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_resacb;
	move_chan_args.fr_objid = resa_objid[1];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_resacb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = resa_objid[1],			
		       targetid = resa_objid[7] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nResA1.acb moved to ResA7.acb\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for ResA1 to ResA7\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[1]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[1], "acb" );

   printf ("----- Dumping ResA[7]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[7], "acb" );

   sts = om$make_message(classname = "ResB",
                         methodname = "show_b",
                         size = 0,
                         p_arglist = 0,
                         p_msg = &showresb);
   if(!(sts&1))
   {
	printf("error in om%make_message for show_b\n");
	om$report_error(sts = sts);
	exit();
   }
   chansel.type = OM_e_name;
   chansel.u_sel.name = chan_resacb;
   sts = om$send(mode = OM_e_wrt_object,
                 msg = &showresb,
                 senderid = resa_objid[7],
                 p_chanselect = &chansel);
   if(!(sts&1))
   {
	printf("error in om$send (show_b)\n");
	om$report_error(sts = sts);
	exit();
   }

/******************************************************************
Test # 3 - Source is on the TO side of a relation.
*******************************************************************/

   printf ("\n\n******* Test 3 - ResA2.acb to ResA8.acb\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_resacb;
	move_chan_args.fr_objid = resa_objid[2];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_resacb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = resa_objid[2],			
		       targetid = resa_objid[8] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nResA2.acb moved to ResA8.acb\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for ResA2 to ResA8\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[2]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[2], "acb" );

   printf ("----- Dumping ResA[8]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[8], "acb" );

   chansel.type = OM_e_name;
   chansel.u_sel.name = chan_resacb;
   sts = om$send(mode = OM_e_wrt_object,
                 msg = &showresb,
                 senderid = resa_objid[8],
                 p_chanselect = &chansel);
   if(!(sts&1))
   {
	printf("error in om$send (show_b)\n");
	om$report_error(sts = sts);
	exit();
   }

/******************************************************************
Test # 4 - Source is on the FROM side of a relation.
*******************************************************************/

   printf ("\n\n******* Test 4 - ResA4.acb to ResA9.acb\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_resacb;
	move_chan_args.fr_objid = resa_objid[4];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_resacb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = resa_objid[4],			
		       targetid = resa_objid[9] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nResA4.acb moved to ResA9.acb\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for ResA4 to ResA9\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[4]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[4], "acb" );

   printf ("----- Dumping ResA[9]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[9], "acb" );

   chansel.type = OM_e_name;
   chansel.u_sel.name = chan_resacb;
   sts = om$send(mode = OM_e_wrt_object,
                 msg = &showresb,
                 senderid = resa_objid[9],
                 p_chanselect = &chansel);
   if(!(sts&1))
   {
	printf("error in om$send (show_b)\n");
	om$report_error(sts = sts);
	exit();
   }

/******************************************************************
Test # 5 - Source is a dipole and target is a dipole.  This should 
           generate a error because the target should be empty.
*******************************************************************/

   printf ("\n\n******* Test 5 - ResA5.acb to ResA10.acb but ResA10.acb is not empty\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_resacb;
	move_chan_args.fr_objid = resa_objid[5];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_resacb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = resa_objid[5],			
		       targetid = resa_objid[10] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nResA5.acb moved to ResA10\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("\nOM_E_INVCHAN - expected error\n\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for ResA5 to ResA10\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[5]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[5], "acb" );

   printf ("----- Dumping ResA[10]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[10], "acb" );

/******************************************************************
Test # 6 - Source is a dipole and its channel has only ResBs on rhs.  
           Target is empty and its channel accepts ResBs & Cs on rhs.
	   Target channel is a superset of Source's channel.
*******************************************************************/

   printf ("\n\n******* Test 6 - ResA7.acb to ResA1.acbc - should error\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_resacbc;
	move_chan_args.fr_objid = resa_objid[7];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_resacb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = resa_objid[7],			
		       targetid = resa_objid[1] );

   switch(sts)
   {
      case OM_I_CHAN_EMPTY:
      case OM_S_SUCCESS:  printf("\n\nResA7.acb moved to ResA1.acbc\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      case OM_E_CLASS_CONFLICT:
                           printf("\nOM_E_CLASS_CONFLICT - expected error\n");
                           break;
      default:				
         printf("error in om$send (move_chan) for ResA7.acb to ResA1.acbc\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[7]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[7], "acb" );

   printf ("----- Dumping ResA[1]'s acbc channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[1], "acbc" );

/******************************************************************
Test # 7 - Source is FROM side of relation and its channel has
		 only ResBs on rhs.  
           Target is empty and its channel accepts any class on rhs.
	   Target channel is a wildcard channel.
*******************************************************************/

   printf ("\n\n******* Test 7 - ResA9.acb to ResA10.acany - should error\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_resacany;
	move_chan_args.fr_objid = resa_objid[9];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_resacb;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = resa_objid[9],			
		       targetid = resa_objid[10] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nResA9.acb moved to ResA10.acany\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      case OM_E_CLASS_CONFLICT:
                           printf("\nOM_E_CLASS_CONFLICT - expected error\n");
                           break;
      default:				
         printf("error in om$send (move_chan) for ResA9.acb to ResA10.acany\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[9]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[9], "acb" );

   printf ("----- Dumping ResA[10]'s acany channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[10], "acany" );

/******************************************************************
Test # 8 - Source is FROM side of relation and its channel has
	    only any class on rhs.  
           Target is empty and its channel accepts ResBs & Cs on rhs.
	   Target channel is a subset of source channel but all
	    objects currently hooked to channel are allowed on source.
*******************************************************************/

   printf ("\n\n******* Test 8 - ResA10.acany to ResA4.acbc but Res10.acany is empty\n");

	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_resacbc;
	move_chan_args.fr_objid = resa_objid[10];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_resacany;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = resa_objid[10],			
		       targetid = resa_objid[4] );

   switch(sts)
   {
      case OM_S_SUCCESS:  printf("\n\nResA10.acany moved to ResA4.acbc\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("an invalid channel was used\n");
      		          break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      case OM_I_CHAN_EMPTY:
                           printf("\nOM_I_CHAN_EMPTY - expected status\n");
                           break;
      default:				
         printf("error in om$send (move_chan) for ResA10.acany to ResA4.acbc\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[10]'s acany channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[10], "acany" );

   printf ("----- Dumping ResA[4]'s acbc channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[4], "acbc" );

/* Construct a C object and connect it to ResA[4].acbc */

      sts = om$construct(osname = "OM_TransOS_0",
                         classname = "C",
                         p_objid = &c2_objid,
                         neighbor = OM_GS_NULL_NEIGHBOR);
      if (!(sts&1))
      {
         printf (" error in om$construct for C2\n" );
         om$report_error(sts = sts);
         exit();
      }

	connect_args.to_sel.type = OM_e_name;
	connect_args.to_sel.u_sel.name = chan_sca;
	connect_args.to_idx = 0;
	connect_args.fr_objid = resa_objid[4];
	connect_args.fr_os = OM_Gw_current_OS;
	connect_args.fr_sel.type = OM_e_name;
	connect_args.fr_sel.u_sel.name = chan_resacbc;
	connect_args.fr_idx            = 0;

	sts = om$send (msg = &connect_msg,			
		       senderid = resa_objid[4],			
		       targetid = c2_objid );
 
   if (!(sts&1))
      {
      printf (" error in om$send (connect) for C2\n");
      om$report_error(sts = sts);
      exit();
      }

   printf ("ResA4 connected to C2\n");

   printf ("----- Dumping ResA[4]'s acbc channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[4], "acbc" );

   printf ("----- Dumping C2's sca channel\n");
   OMT_dump_relation( OM_Gw_current_OS, c2_objid, "sca" );
   

/******************************************************************
Test # 9 - Source is FROM side of relation and its channel has
	    ResBs and C2s on rhs.  
           Target is empty and its channel accepts only ResBs on rhs.
	   Target channel is a subset of source channel but all
	    objects currently hooked to channel are not allowed
	    on source.  This test should fail.
*******************************************************************/

   printf ("\n\n******* Test 9 - ResA4.acbc to ResA9.acb but C2 is not allowed on acb\n");
	move_chan_args.to_sel.type = OM_e_name;
	move_chan_args.to_sel.u_sel.name = chan_resacb;
	move_chan_args.fr_objid = resa_objid[4];
	move_chan_args.fr_os = OM_Gw_current_OS;
	move_chan_args.fr_sel.type = OM_e_name;
	move_chan_args.fr_sel.u_sel.name = chan_resacbc;

	sts = om$send (msg = &move_chan_msg,			
		       senderid = resa_objid[4],			
		       targetid = resa_objid[9] );

   switch(sts)
   {
      case OM_I_CHAN_EMPTY:
      case OM_S_SUCCESS:  printf("\n\nResA4.acbc moved to ResA9.acb\n");
      			  break;
      case OM_E_CHAN_NOTEMPTY: printf("Channel is not empty\n");
      			       break;
      case OM_E_INVCHAN:  printf("\nOM_E_INVCHAN - expected error\n");
      		          break;
      case OM_E_CLASS_CONFLICT: 
                         printf ("\nOM_E_CLASS_CONFLICT - expected error\n\n");
                         break;
      case OM_E_REL_MISMATCH:  printf("relations don't match\n");
      				break;
      default:				
         printf("error in om$send (move_chan) for ResA4.acbc to ResA9.acb\n");
         om$report_error(sts = sts);
   }
   printf ("----- Dumping ResA[4]'s acbc channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[4], "acbc" );

   printf ("----- Dumping ResA[9]'s acb channel\n");
   OMT_dump_relation( OM_Gw_current_OS, resa_objid[9], "acb" );

return(1);
}  /* main */
Exemplo n.º 4
0
bool SwapEnds::move(VRP *V, int a, int v)
{
    ///
    /// This function takes the routes corresponding to nodes a and v
    /// and swaps the ends of these routes following a and v respectively.
    /// Example:  VRPH_DEPOT-i-a-j-k-l-VRPH_DEPOT and VRPH_DEPOT-t-u-v-x-y-z-VRPH_DEPOT becomes
    /// VRPH_DEPOT-i-a-x-y-z-VRPH_DEPOT and VRPH_DEPOT-t-u-v-j-k-l-VRPH_DEPOT.
    /// If the proposed move is feasible, all solution modifications
    /// are made, and the function returns true.  Returns false if the move
    /// is infeasible.
    ///
    

    VRPMove M;

    if(evaluate(V,a,v,&M)==false)
        return false;    // move is infeasible

    int current_node, a_start, a_end, v_start, v_end;
    int route_after_a, route_before_a, route_before_v, route_after_v;
    int  n, u, b;


#if SWAP_ENDS_DEBUG>0
        printf("Calling swap ends(%d,%d)\n",a,v);
#endif
    

    if(a==VRPH_DEPOT || v==VRPH_DEPOT)
        report_error("%s: Swap ends called with depot; Move doesn't make sense\n",__FUNCTION__);
    

    n = V->num_nodes;

    if(V->route_num[a] == V->route_num[v])
        report_error("%s: swap ends called with a and v in same route!\n",__FUNCTION__);

#if SWAP_VERIFY
    V->verify_routes("SWAP_ENDS::prior to move\n");
#endif

    V->update(&M);

    a_end = V->route[V->route_num[a]].end;
    a_start = V->route[V->route_num[a]].start;
    
    route_after_a = V->route_num[-V->next_array[a_end]];
    route_before_a = V->route_num[-V->pred_array[a_start]];

    v_end = V->route[V->route_num[v]].end;
    v_start = V->route[V->route_num[v]].start;
    
    route_after_v = V->route_num[-V->next_array[v_end]];
    route_before_v = V->route_num[-V->pred_array[v_start]];
    
    u = V->next_array[v];
    b = V->next_array[a];

    if(u==VRPH_DEPOT || b==VRPH_DEPOT)
    {
        report_error("%s: u=0 or b=0 in swap_ends\n",__FUNCTION__);

    }

    if(u>0 && b>0)
    {
        V->next_array[a]=u;
        V->pred_array[u]=a;
        V->next_array[v]=b;
        V->pred_array[b]=v;
    }
    else
    {
        if(u>0 && b<0)
        {
            V->next_array[a]=u;
            V->pred_array[u]=a;
            V->next_array[v]=b;
            V->pred_array[-b]=-v;
        }
        else
        {

            if(u<0 && b>0)
            {
                V->next_array[a]=u;
                V->pred_array[-u]=-a;
                V->next_array[v]=-b;
                V->pred_array[b]=v;
            }
            else
                report_error("%s: Reached strange place...\n",__FUNCTION__);
        }
    }

    

    // Now update the start, end, length, and load info for V->route_num[a] and V->route_num[v]

    
    V->route[V->route_num[a]].start = a_start;
    V->route[V->route_num[a]].end = v_end;

    
    V->route[V->route_num[v]].start = v_start;
    V->route[V->route_num[v]].end = a_end;

    // Now update the route_num-looping...
    
    current_node = a;
    while(current_node > 0)
    {
        V->route_num[current_node] = V->route_num[a];
        current_node = V->next_array[current_node];
        
    }

    current_node = v;
    while(current_node > 0)
    {
        V->route_num[current_node] = V->route_num[v];
        current_node = V->next_array[current_node];

    }

    // Now we have to update the routes following the modified a and v routes

    // Get the new start and end values 
    a_start = V->route[V->route_num[a]].start;
    v_start = V->route[V->route_num[v]].start;
    a_end = V->route[V->route_num[a]].end;
    v_end = V->route[V->route_num[v]].end;


    if(route_after_a != V->route_num[v] && route_after_v != V->route_num[a])
    {
        

        // Simple case - just switch the two
        if(route_after_a != 0 && route_after_v!=0)
        {
            
            V->next_array[a_end] = -V->route[route_after_a].start;
            V->pred_array[V->route[route_after_a].start] = -a_end;

            V->next_array[v_end] = -V->route[route_after_v].start;
            V->pred_array[V->route[route_after_v].start] = -v_end;

            return true;
        }

        if(route_after_a == 0)
        {
            V->next_array[a_end] = VRPH_DEPOT;
            V->pred_array[VRPH_DEPOT] = -a_end;

            V->next_array[v_end] = -V->route[route_after_v].start;
            V->pred_array[V->route[route_after_v].start] = -v_end;


            return true;
        }

        if(route_after_v == 0)
        {
            
            V->next_array[v_end] = VRPH_DEPOT;
            V->pred_array[VRPH_DEPOT] = -v_end;

            V->next_array[a_end] = -V->route[route_after_a].start;
        
            V->pred_array[V->route[route_after_a].start] = -a_end;

            return true;
        }
    }

    
    if(route_after_a == V->route_num[v] && route_after_v == V->route_num[a])
    {
        // If we don't change anything here, then the new V->route_num[v] will point to itself!
        // To fix this, make the new_v_route point 
        
        V->next_array[a_end] = -v_start;
        V->pred_array[v_start] = -a_end;

        V->next_array[v_end] = -a_start;
        V->pred_array[a_start] = -v_end;

        return true;

        
    }

    
    if(route_after_a == V->route_num[v])
    {
        
        // If we don't change anything here, then the new V->route_num[v] will point to itself!
        
        V->next_array[a_end] = -v_start;
        V->pred_array[v_start] = -a_end;

        if(route_after_v != VRPH_DEPOT)
        {
            V->next_array[v_end] = -V->route[route_after_v].start;
            V->pred_array[V->route[route_after_v].start] = -v_end;
        }
        else
        {
            V->next_array[v_end] = VRPH_DEPOT;
            V->pred_array[VRPH_DEPOT] = -v_end;
        }

#if SWAP_ENDS_VERIFY
        V->verify_routes("SwapEnds 5\n");
#endif

        return true;

        
    }

    if(route_after_v == V->route_num[a])
    {        
            
        // If we don't change anything here, then the new V->route_num[a] will point to itself!
        
        V->next_array[v_end] = -a_start;
        V->pred_array[a_start] = -v_end;

        if(route_after_a!=VRPH_DEPOT)
        {
            V->next_array[a_end] = -V->route[route_after_a].start;
            V->pred_array[V->route[route_after_a].start] = -a_end;
        }
        else
        {
            V->next_array[a_end] = VRPH_DEPOT;
            V->pred_array[VRPH_DEPOT] = -a_end;
        }



        return true;


    }

    report_error("%s: should never be here\n",__FUNCTION__);

    return false;


}
Exemplo n.º 5
0
  std::pair<double, double> BinomialLogitPartialAugmentationDataImputer::impute(
      RNG &rng, double number_of_trials, double number_of_successes,
      double linear_predictor) const {
    if (number_of_successes > number_of_trials) {
      ostringstream err;
      err << "The number of successes must not exceed the number of trials "
          << "in BinomialLogitPartialAugmentationDataImputer::impute()."
          << endl;
      debug_status_message(err, number_of_trials, number_of_successes,
                           linear_predictor);
      report_error(err.str());
    }
    if (number_of_successes < 0 || number_of_trials < 0) {
      ostringstream err;
      err << "The number of successes and the number of trials must both "
          << "be non-negative in "
          << "BinomialLogitPartialAugmentationDataImputer::impute()." << endl;
      debug_status_message(err, number_of_trials, number_of_successes,
                           linear_predictor);
      report_error(err.str());
    }
    double information_weighted_sum = 0;
    double information = 0;
    if (number_of_trials < clt_threshold_) {
      for (int i = 0; i < number_of_trials; ++i) {
        bool success = i < number_of_successes;
        double latent_logit = rtrun_logit_mt(rng, linear_predictor, 0, success);
        // mu is unused because the mixture is a scale-mixture only,
        // but we need it for the API.
        double mu, sigsq;
        mixture_approximation.unmix(rng, latent_logit - linear_predictor, &mu,
                                    &sigsq);
        double current_weight = 1.0 / sigsq;
        information += current_weight;
        information_weighted_sum += latent_logit * current_weight;
      }
    } else {
      // Large sample case.  There are number_of_successes draws from
      // the positive side, and number_of_trials - number_of_successes
      // draws from the negative side.
      double mean_of_logit_sum = 0;
      double variance_of_logit_sum = 0;
      if (number_of_successes > 0) {
        mean_of_logit_sum +=
            number_of_successes * trun_logit_mean(linear_predictor, 0, true);
        variance_of_logit_sum += number_of_successes *
                                 trun_logit_variance(linear_predictor, 0, true);
      }
      double number_of_failures = number_of_trials - number_of_successes;
      if (number_of_failures > 0) {
        mean_of_logit_sum +=
            number_of_failures * trun_logit_mean(linear_predictor, 0, false);
        variance_of_logit_sum +=
            number_of_failures *
            trun_logit_variance(linear_predictor, 0, false);
      }
      // The information_weighted_sum is the sum of the latent logits
      // (approximated by a normal), divided by the weight that each
      // term in the sum recieves (the variance of the logistic
      // distribution, pi^2/3).
      information_weighted_sum =
          rnorm_mt(rng, mean_of_logit_sum, sqrt(variance_of_logit_sum));
      information_weighted_sum /= Constants::pi_squared_over_3;

      // Each latent logit carries the same amount of information:
      // 1/pi_squared_over_3.
      information = number_of_trials / Constants::pi_squared_over_3;
    }
    return std::make_pair(information_weighted_sum, information);
  }
Exemplo n.º 6
0
/*! \brief
 * Checks the validity of parameters.
 *
 * \param[in]     fp      File handle to use for diagnostic messages
 *   (can be NULL).
 * \param[in]     name    Name of the method (used for error messages).
 * \param[in]     nparams Number of parameters in \p param.
 * \param[in,out] param   Parameter array
 *   (only the \c flags field of boolean parameters may be modified).
 * \param[in]     symtab  Symbol table (used for checking overlaps).
 * \returns       true if there are no problems with the parameters,
 *   false otherwise.
 *
 * This function performs some checks common to both check_method() and
 * check_modifier().
 * The purpose of these checks is to ensure that the selection parser does not
 * need to check for the validity of the parameters at each turn, and to
 * report programming errors as early as possible.
 * If you remove a check, make sure that the parameter parser can handle the
 * resulting parameters.
 */
static bool
check_params(FILE *fp, const char *name, int nparams, gmx_ana_selparam_t param[],
             const gmx::SelectionParserSymbolTable &symtab)
{
    bool              bOk = true;
    int               i, j;

    if (nparams > 0 && !param)
    {
        report_error(fp, name, "error: missing parameter data");
        return false;
    }
    if (nparams == 0 && param)
    {
        report_error(fp, name, "warning: parameter data unused because nparams=0");
    }
    /* Check each parameter */
    for (i = 0; i < nparams; ++i)
    {
        /* Check that there is at most one NULL name, in the beginning */
        if (param[i].name == NULL && i > 0)
        {
            report_error(fp, name, "error: NULL parameter should be the first one");
            bOk = false;
            continue;
        }
        /* Check for duplicates */
        for (j = 0; j < i; ++j)
        {
            if (param[j].name == NULL)
            {
                continue;
            }
            if (!gmx_strcasecmp(param[i].name, param[j].name))
            {
                report_error(fp, name, "error: duplicate parameter name '%s'", param[i].name);
                bOk = false;
                break;
            }
        }
        /* Check flags */
        if (param[i].flags & SPAR_SET)
        {
            report_param_error(fp, name, param[i].name, "warning: flag SPAR_SET is set");
            param[i].flags &= ~SPAR_SET;
        }
        if (param[i].flags & SPAR_RANGES)
        {
            if (param[i].val.type != INT_VALUE && param[i].val.type != REAL_VALUE)
            {
                report_param_error(fp, name, param[i].name, "error: SPAR_RANGES cannot be set for a non-numeric parameter");
                bOk = false;
            }
            if (param[i].flags & SPAR_DYNAMIC)
            {
                report_param_error(fp, name, param[i].name, "warning: SPAR_DYNAMIC does not have effect with SPAR_RANGES");
                param[i].flags &= ~SPAR_DYNAMIC;
            }
            if (!(param[i].flags & SPAR_VARNUM) && param[i].val.nr != 1)
            {
                report_param_error(fp, name, param[i].name, "error: range should take either one or an arbitrary number of values");
                bOk = false;
            }
            if (param[i].flags & SPAR_ATOMVAL)
            {
                report_param_error(fp, name, param[i].name, "error: SPAR_RANGES and SPAR_ATOMVAL both set");
                bOk = false;
            }
        }
        if ((param[i].flags & SPAR_VARNUM) && (param[i].flags & SPAR_ATOMVAL))
        {
            report_param_error(fp, name, param[i].name, "error: SPAR_VARNUM and SPAR_ATOMVAL both set");
            bOk = false;
        }
        if (param[i].flags & SPAR_ENUMVAL)
        {
            if (param[i].val.type != STR_VALUE)
            {
                report_param_error(fp, name, param[i].name, "error: SPAR_ENUMVAL can only be set for string parameters");
                bOk = false;
            }
            if (param[i].val.nr != 1)
            {
                report_param_error(fp, name, param[i].name, "error: SPAR_ENUMVAL parameters should take exactly one value");
                bOk = false;
            }
            if (param[i].flags & (SPAR_DYNAMIC | SPAR_VARNUM | SPAR_ATOMVAL))
            {
                report_param_error(fp, name, param[i].name, "error: only SPAR_OPTIONAL supported with SPAR_ENUMVAL");
                bOk = false;
            }
        }
        /* Check boolean parameters */
        if (param[i].val.type == NO_VALUE)
        {
            if (param[i].val.nr != 0)
            {
                report_param_error(fp, name, param[i].name, "error: number of values should be zero for boolean parameters");
                bOk = false;
            }
            /* The boolean parameters should always be optional, so set the
             * flag for convenience. */
            param[i].flags |= SPAR_OPTIONAL;
            /* Any other flags should not be specified */
            if (param[i].flags & ~SPAR_OPTIONAL)
            {
                report_param_error(fp, name, param[i].name, "error: boolean parameter should not have any flags set");
                bOk = false;
            }
        }
        /* Check val.nr */
        if (param[i].flags & (SPAR_VARNUM | SPAR_ATOMVAL))
        {
            if (param[i].val.nr != -1)
            {
                report_param_error(fp, name, param[i].name, "warning: val.nr is not -1 although SPAR_VARNUM/SPAR_ATOMVAL is set");
            }
            param[i].val.nr = -1;
        }
        else if (param[i].val.type != NO_VALUE)
        {
            if (param[i].val.nr <= 0)
            {
                report_param_error(fp, name, param[i].name, "error: val.nr <= 0");
                bOk = false;
            }
        }
        /* Check that the value pointer is NULL */
        if (param[i].nvalptr != NULL)
        {
            report_param_error(fp, name, param[i].name, "warning: nvalptr is set");
        }
        if (param[i].val.u.ptr != NULL && !(param[i].flags & SPAR_ENUMVAL))
        {
            report_param_error(fp, name, param[i].name, "warning: value pointer is set");
        }
        /* Check that the name contains only valid characters */
        if (param[i].name == NULL)
        {
            continue;
        }
        if (!isalpha(param[i].name[0]))
        {
            report_param_error(fp, name, param[i].name, "error: name does not begin with a letter");
            bOk = false;
            continue;
        }
        for (j = 1; param[i].name[j] != 0; ++j)
        {
            if (param[i].name[j] != '_' && !isalnum(param[i].name[j]))
            {
                report_param_error(fp, name, param[i].name, "error: name contains non-alphanumeric characters");
                bOk = false;
                break;
            }
        }
        if (param[i].name[j] != 0)
        {
            continue;
        }
        /* Check that the name does not conflict with a method */
        if (symtab.findSymbol(param[i].name))
        {
            report_param_error(fp, name, param[i].name, "error: name conflicts with another method or a keyword");
            bOk = false;
        }
    } /* End of parameter loop */
      /* Check parameters of existing methods */
    gmx::SelectionParserSymbolIterator symbol
        = symtab.beginIterator(gmx::SelectionParserSymbol::MethodSymbol);
    while (symbol != symtab.endIterator())
    {
        gmx_ana_selmethod_t *method = symbol->methodValue();
        gmx_ana_selparam_t  *param  =
            gmx_ana_selmethod_find_param(name, method);
        if (param)
        {
            report_param_error(fp, method->name, param->name, "error: name conflicts with another method or a keyword");
            bOk = false;
        }
        ++symbol;
    }
    return bOk;
}
Exemplo n.º 7
0
static __libcobalt_ctor void __init_cobalt(void)
{
	pthread_t ptid = pthread_self();
	struct sched_param parm;
	int policy, ret;
	const char *p;

	p = getenv("XENO_CONFIG_OUTPUT");
	if (p && *p) {
		dump_configuration();
		_exit(0);
	}

#ifndef CONFIG_SMP
	ret = get_static_cpu_count();
	if (ret > 0)
		report_error("running non-SMP libraries on SMP kernel?");
#endif

	__cobalt_main_ptid = ptid;
	cobalt_default_mutexattr_init();
	cobalt_default_condattr_init();

	if (__cobalt_defer_init)
		return;

	__libcobalt_init();

	if (__cobalt_no_shadow)
		return;

	p = getenv("XENO_NOSHADOW");
	if (p && *p)
		return;

	ret = __STD(pthread_getschedparam(ptid, &policy, &parm));
	if (ret) {
		report_error("pthread_getschedparam: %s", strerror(ret));
		exit(EXIT_FAILURE);
	}

	/*
	 * Switch the main thread to a Xenomai shadow.
	 * __cobalt_main_prio might have been overriden by
	 * some compilation unit which has been linked in, to force
	 * the scheduling parameters. Otherwise, the current policy
	 * and priority are reused, for declaring the thread to the
	 * Xenomai scheduler.
	 *
	 * SCHED_FIFO is assumed for __cobalt_main_prio > 0.
	 */
	if (__cobalt_main_prio > 0) {
		policy = SCHED_FIFO;
		parm.sched_priority = __cobalt_main_prio;
	} else if (__cobalt_main_prio == 0) {
		policy = SCHED_OTHER;
		parm.sched_priority = 0;
	}

	ret = __RT(pthread_setschedparam(ptid, policy, &parm));
	if (ret) {
		report_error("pthread_setschedparam: %s", strerror(ret));
		exit(EXIT_FAILURE);
	}
}
Exemplo n.º 8
0
double VRP::SA_solve(int heuristics, double start_temp, double cool_ratio,
                     int iters_per_loop, int num_loops, int nlist_size, bool verbose)    
{
    ///
    /// Uses the given parameters to generate a VRP solution using Simulated Annealing.
    /// Assumes that data has already been imported into V and that we have
    /// some existing solution.  Returns the total route length of the best solution found.
    ///

    this->temperature = start_temp;
    this->cooling_ratio = cool_ratio;

    int ctr, n, j,  i,  R, rules, random, fixed, neighbor_list, objective;

    if(heuristics & VRPH_RANDOMIZED)
        random=VRPH_RANDOMIZED;
    else
        random=0;

    if(heuristics & VRPH_FIXED_EDGES)
        fixed=VRPH_FIXED_EDGES;
    else
        fixed=0;

    if(heuristics & VRPH_USE_NEIGHBOR_LIST)
        neighbor_list=VRPH_USE_NEIGHBOR_LIST;
    else
        neighbor_list=0;

    objective=VRPH_SAVINGS_ONLY;
    // default strategy

    if(heuristics & VRPH_MINIMIZE_NUM_ROUTES)
        objective=VRPH_MINIMIZE_NUM_ROUTES;
    
    n=num_nodes;

    // The perm[] array will contain all the nodes in the current solution
    int *perm;
    perm=new int[this->num_nodes];
    j=VRPH_ABS(this->next_array[VRPH_DEPOT]);
    for(i=0;i<this->num_nodes;i++)
    {
        perm[i]=j;
        if(!routed[j])
            report_error("%s: Unrouted node in solution!!\n");

        j=VRPH_ABS(this->next_array[j]);
    }
    if(j!=VRPH_DEPOT)
        report_error("%s: VRPH_DEPOT is not last node in solution!!\n");

    // Define the heuristics we may use

    OnePointMove OPM;
    TwoPointMove TPM;
    TwoOpt         TO;
    OrOpt         OR;
    ThreeOpt     ThreeO;
    CrossExchange    CE;
    ThreePointMove ThreePM;

    double start_val;

    this->export_solution_buff(this->best_sol_buff);
    // We are assuming we have an existing solution

    // Set the neighbor list size used in the improvement search
    this->neighbor_list_size=VRPH_MIN(nlist_size, num_nodes);

    best_total_route_length=this->total_route_length;
    normalize_route_numbers();

    ctr=0;

    // The idea is to perform num_loops loops of num_iters iterations each.
    // For each iteration, run through the given heuristic operation at random
    // and perform a Simulated Annealing search.

    rules=VRPH_USE_NEIGHBOR_LIST+VRPH_FIRST_ACCEPT+VRPH_SIMULATED_ANNEALING+VRPH_SAVINGS_ONLY;

    double worst_obj=0;
    for(ctr=0;ctr<num_loops;ctr++)
    {
        if(verbose)
        {
            printf("\nctr=%d of %d, temp=%f, obj=%f (overall best=%f; worst=%f)\n",ctr,num_loops,
                this->temperature, 
                this->total_route_length,this->best_total_route_length,worst_obj);
            fflush(stdout);
        }
        // Reset worst_obj;
        worst_obj=0;

        // Cool it...
        this->temperature = this->cooling_ratio * this->temperature;


        for(int k=0; k < iters_per_loop; k++)
        {
            start_val=total_route_length;
            if(heuristics & THREE_OPT)
            {
                rules=VRPH_SIMULATED_ANNEALING+VRPH_INTRA_ROUTE_ONLY+random+fixed+objective;
                normalize_route_numbers();
                R=total_number_of_routes;
                for(i=1; i<=R; i++)    
                {
                    ThreeO.route_search(this,i,rules);
                    if(this->total_route_length > worst_obj)
                        worst_obj=this->total_route_length;
                }

            }


            if(heuristics & ONE_POINT_MOVE)
            {
                rules=VRPH_SIMULATED_ANNEALING+neighbor_list+random+fixed+objective;
                if(random)
                    random_permutation(perm, this->num_nodes);

                for(i=1;i<=n;i++)    
                {

                    OPM.search(this,perm[i-1],rules);
                    if(this->total_route_length > worst_obj)
                        worst_obj=this->total_route_length;
                }

            }



            if(heuristics & TWO_POINT_MOVE)
            {
                rules=VRPH_SIMULATED_ANNEALING+neighbor_list+random+fixed+objective;
                if(random)
                    random_permutation(perm, this->num_nodes);

                for(i=1;i<=n;i++)    
                {
                    TPM.search(this,perm[i-1],rules);
                    if(this->total_route_length > worst_obj)
                        worst_obj=this->total_route_length;
                }


            }



            if(heuristics & TWO_OPT)
            {

                rules=VRPH_SIMULATED_ANNEALING+neighbor_list+random+fixed+objective;
                if(random)
                    random_permutation(perm, this->num_nodes);

                for(i=1;i<=n;i++)    
                {
                    TO.search(this,perm[i-1],rules);
                    if(this->total_route_length > worst_obj)
                        worst_obj=this->total_route_length;
                }


            }        

            if(heuristics & THREE_POINT_MOVE)
            {
                rules=VRPH_SIMULATED_ANNEALING+VRPH_INTER_ROUTE_ONLY+neighbor_list+random+fixed+objective;
                if(random)
                    random_permutation(perm, this->num_nodes);


                for(i=1;i<=n;i++)    
                {
                    ThreePM.search(this,perm[i-1],rules);
                    if(this->total_route_length > worst_obj)
                        worst_obj=this->total_route_length;
                }
            }

            if(heuristics & OR_OPT)
            {
                rules=VRPH_SIMULATED_ANNEALING+neighbor_list+random+fixed+objective;
                if(random)
                    random_permutation(perm, this->num_nodes);

                for(i=1;i<=n;i++)    
                {
                    OR.search(this,perm[i-1],3,rules);
                    if(this->total_route_length > worst_obj)
                        worst_obj=this->total_route_length;
                }

                for(i=1;i<=n;i++)    
                {
                    OR.search(this,perm[i-1],2,rules);
                    if(this->total_route_length > worst_obj)
                        worst_obj=this->total_route_length;
                }


            }

            if(heuristics & CROSS_EXCHANGE)
            {
                normalize_route_numbers();
                this->find_neighboring_routes();
                R=total_number_of_routes;
                rules=VRPH_SIMULATED_ANNEALING+fixed+objective;
                if(random)
                    random_permutation(perm, this->num_nodes);


                for(i=1; i<=R-1; i++)    
                {
                    for(j=0;j<=1;j++)
                    {
                        CE.route_search(this,i, route[i].neighboring_routes[j],rules);
                        if(this->total_route_length > worst_obj)
                            worst_obj=this->total_route_length;
                    }
                }
            }            
        }
    }

    delete [] perm;

    // Restore the best sol
    this->import_solution_buff(this->best_sol_buff);
    // Now return the obj. function value

    if(has_service_times==false)
        return this->best_total_route_length;
    else
        return this->best_total_route_length-total_service_time;

}
Exemplo n.º 9
0
double pnt(double t, double df, double delta, int lower_tail, int log_p)
{
    double a, albeta, b, del, errbd, geven, godd,
        lambda, p, q, rxb, s, tnc, tt, x, xeven, xodd;
    int it, negdel;

    /* note - itrmax and errmax may be changed to suit one's needs. */

    const int itrmax = 1000;
    const double errmax = 1.e-12;

    if (df <= 0.) ML_ERR_return_NAN;

    if(!R_FINITE(t))
        return (t < 0) ? R_DT_0 : R_DT_1;
    if (t >= 0.) {
        negdel = false; tt = t;         del = delta;
    }
    else {
        negdel = true;          tt = -t;        del = -delta;
    }

    if (df > 4e5 || del*del > 2*M_LN2*(-(numeric_limits<double>::min_exponent))) {
        /*-- 2nd part: if del > 37.62, then p=0 below
          FIXME: test should depend on `df', `tt' AND `del' ! */
        /* Approx. from  Abramowitz & Stegun 26.7.10 (p.949) */
        s = 1./(4.*df);

        return pnorm(tt*(1. - s), del, sqrt(1. + tt*tt*2.*s),
                     lower_tail != negdel, log_p);
    }

    /* initialize twin series */
    /* Guenther, J. (1978). Statist. Computn. Simuln. vol.6, 199. */

    x = t * t;
    x = x / (x + df);/* in [0,1) */
    if (x > 0.) {/* <==>  t != 0 */
        lambda = del * del;
        p = .5 * exp(-.5 * lambda);
        if(p == 0.) { /* underflow! */
            /*========== really use an other algorithm for this case !!! */
            ML_ERROR(ME_UNDERFLOW);
            report_error("|delta| too large."); /* |delta| too large */
        }
        q = M_SQRT_2dPI * p * del;
        s = .5 - p;
        a = .5;
        b = .5 * df;
        rxb = pow(1. - x, b);
        albeta = M_LN_SQRT_PI + lgammafn(b) - lgammafn(.5 + b);
        xodd = pbeta(x, a, b, /*lower*/true, /*log_p*/false);
        godd = 2. * rxb * exp(a * log(x) - albeta);
        xeven = 1. - rxb;
        geven = b * x * rxb;
        tnc = p * xodd + q * xeven;

        /* repeat until convergence or iteration limit */
        for(it = 1; it <= itrmax; it++) {
            a += 1.;
            xodd  -= godd;
            xeven -= geven;
            godd  *= x * (a + b - 1.) / a;
            geven *= x * (a + b - .5) / (a + .5);
            p *= lambda / (2 * it);
            q *= lambda / (2 * it + 1);
            tnc += p * xodd + q * xeven;
            s -= p;
            if(s <= 0.) { /* happens e.g. for (t,df,delta)=(40,10,38.5), after 799 it.*/
                ML_ERROR(ME_PRECISION);
                goto finis;
            }
            errbd = 2. * s * (xodd - godd);
            if(errbd < errmax) goto finis;/*convergence*/
        }
        /* non-convergence:*/
        ML_ERROR(ME_PRECISION);
    }
    else { /* x = t = 0 */
        tnc = 0.;
    }
 finis:
    tnc += pnorm(- del, 0., 1., /*lower*/true, /*log_p*/false);

    lower_tail = lower_tail != negdel; /* xor */
    return R_DT_val(tnc);
}
Exemplo n.º 10
0
int plan(struct diveplan *diveplan, char **cached_datap, bool is_planner, bool show_disclaimer)
{
	struct sample *sample;
	int po2;
	int transitiontime, gi;
	int current_cylinder;
	unsigned int stopidx;
	int depth;
	double tissue_tolerance = 0.0;
	struct gaschanges *gaschanges = NULL;
	int gaschangenr;
	int *stoplevels = NULL;
	char *trial_cache = NULL;
	bool stopping = false;
	bool clear_to_ascend;
	int clock, previous_point_time;
	int avg_depth, bottom_time = 0;
	int last_ascend_rate;
	int best_first_ascend_cylinder;
	struct gasmix gas;
	int o2time = 0;
	int breaktime = -1;
	int breakcylinder = 0;
	int error = 0;

	set_gf(diveplan->gflow, diveplan->gfhigh, prefs.gf_low_at_maxdepth);
	if (!diveplan->surface_pressure)
		diveplan->surface_pressure = SURFACE_PRESSURE;
	create_dive_from_plan(diveplan, is_planner);

	/* Let's start at the last 'sample', i.e. the last manually entered waypoint. */
	sample = &displayed_dive.dc.sample[displayed_dive.dc.samples - 1];

	get_gas_at_time(&displayed_dive, &displayed_dive.dc, sample->time, &gas);

	po2 = displayed_dive.dc.sample[displayed_dive.dc.samples - 1].po2.mbar;
	if ((current_cylinder = get_gasidx(&displayed_dive, &gas)) == -1) {
		report_error(translate("gettextFromC", "Can't find gas %s"), gasname(&gas));
		current_cylinder = 0;
	}
	depth = displayed_dive.dc.sample[displayed_dive.dc.samples - 1].depth.mm;
	avg_depth = average_depth(diveplan);
	last_ascend_rate = ascend_velocity(depth, avg_depth, bottom_time);

	/* if all we wanted was the dive just get us back to the surface */
	if (!is_planner) {
		transitiontime = depth / 75; /* this still needs to be made configurable */
		plan_add_segment(diveplan, transitiontime, 0, gas, po2, false);
		create_dive_from_plan(diveplan, is_planner);
		return(error);
	}
	tissue_tolerance = tissue_at_end(&displayed_dive, cached_datap);

#if DEBUG_PLAN & 4
	printf("gas %s\n", gasname(&gas));
	printf("depth %5.2lfm \n", depth / 1000.0);
#endif

	best_first_ascend_cylinder = current_cylinder;
	/* Find the gases available for deco */
	gaschanges = analyze_gaslist(diveplan, &gaschangenr, depth, &best_first_ascend_cylinder);
	/* Find the first potential decostopdepth above current depth */
	for (stopidx = 0; stopidx < sizeof(decostoplevels) / sizeof(int); stopidx++)
		if (decostoplevels[stopidx] >= depth)
			break;
	if (stopidx > 0)
		stopidx--;
	/* Stoplevels are either depths of gas changes or potential deco stop depths. */
	stoplevels = sort_stops(decostoplevels, stopidx + 1, gaschanges, gaschangenr);
	stopidx += gaschangenr;

	/* Keep time during the ascend */
	bottom_time = clock = previous_point_time = displayed_dive.dc.sample[displayed_dive.dc.samples - 1].time.seconds;
	gi = gaschangenr - 1;

	if (best_first_ascend_cylinder != current_cylinder) {
		stopping = true;

		current_cylinder = best_first_ascend_cylinder;
		gas = displayed_dive.cylinder[current_cylinder].gasmix;
#if DEBUG_PLAN & 16
		printf("switch to gas %d (%d/%d) @ %5.2lfm\n", best_first_ascend_cylinder,
		       (get_o2(&gas) + 5) / 10, (get_he(&gas) + 5) / 10, gaschanges[best_first_ascend_cylinder].depth / 1000.0);
#endif
	}
	while (1) {
		/* We will break out when we hit the surface */
		do {
			/* Ascend to next stop depth */
			int deltad = ascend_velocity(depth, avg_depth, bottom_time) * TIMESTEP;
			if (ascend_velocity(depth, avg_depth, bottom_time) != last_ascend_rate) {
				plan_add_segment(diveplan, clock - previous_point_time, depth, gas, po2, false);
				previous_point_time = clock;
				stopping = false;
				last_ascend_rate = ascend_velocity(depth, avg_depth, bottom_time);
			}
			if (depth - deltad < stoplevels[stopidx])
				deltad = depth - stoplevels[stopidx];

			tissue_tolerance = add_segment(depth_to_mbar(depth, &displayed_dive) / 1000.0,
						       &displayed_dive.cylinder[current_cylinder].gasmix,
						       TIMESTEP, po2, &displayed_dive);
			clock += TIMESTEP;
			depth -= deltad;
		} while (depth > stoplevels[stopidx]);

		if (depth <= 0)
			break; /* We are at the surface */

		if (gi >= 0 && stoplevels[stopidx] == gaschanges[gi].depth) {
			/* We have reached a gas change.
			 * Record this in the dive plan */
			plan_add_segment(diveplan, clock - previous_point_time, depth, gas, po2, false);
			previous_point_time = clock;
			stopping = true;

			current_cylinder = gaschanges[gi].gasidx;
			gas = displayed_dive.cylinder[current_cylinder].gasmix;
#if DEBUG_PLAN & 16
			printf("switch to gas %d (%d/%d) @ %5.2lfm\n", gaschanges[gi].gasidx,
			       (get_o2(&gas) + 5) / 10, (get_he(&gas) + 5) / 10, gaschanges[gi].depth / 1000.0);
#endif
			gi--;
		}

		--stopidx;

		/* Save the current state and try to ascend to the next stopdepth */
		int trial_depth = depth;
		cache_deco_state(tissue_tolerance, &trial_cache);
		while (1) {
			/* Check if ascending to next stop is clear, go back and wait if we hit the ceiling on the way */
			clear_to_ascend = true;
			while (trial_depth > stoplevels[stopidx]) {
				int deltad = ascend_velocity(trial_depth, avg_depth, bottom_time) * TIMESTEP;
				if (deltad > trial_depth) /* don't test against depth above surface */
					deltad = trial_depth;
				tissue_tolerance = add_segment(depth_to_mbar(trial_depth, &displayed_dive) / 1000.0,
							       &displayed_dive.cylinder[current_cylinder].gasmix,
							       TIMESTEP, po2, &displayed_dive);
				if (deco_allowed_depth(tissue_tolerance, diveplan->surface_pressure / 1000.0, &displayed_dive, 1) > trial_depth - deltad) {
					/* We should have stopped */
					clear_to_ascend = false;
					break;
				}
				trial_depth -= deltad;
			}
			restore_deco_state(trial_cache);

			if (clear_to_ascend)
				break; /* We did not hit the ceiling */

			/* Add a minute of deco time and then try again */
			if (!stopping) {
				/* The last segment was an ascend segment.
				 * Add a waypoint for start of this deco stop */
				plan_add_segment(diveplan, clock - previous_point_time, depth, gas, po2, false);
				previous_point_time = clock;
				stopping = true;
			}
			tissue_tolerance = add_segment(depth_to_mbar(depth, &displayed_dive) / 1000.0,
						       &displayed_dive.cylinder[current_cylinder].gasmix,
						       DECOTIMESTEP, po2, &displayed_dive);
			cache_deco_state(tissue_tolerance, &trial_cache);
			clock += DECOTIMESTEP;
			/* Finish infinite deco */
			if(clock >= 48 * 3600 && depth >= 6000) {
				error = LONGDECO;
				break;
			}
			if (prefs.doo2breaks) {
				if (get_o2(&displayed_dive.cylinder[current_cylinder].gasmix) == 1000) {
					o2time += DECOTIMESTEP;
					if (o2time >= 12 * 60) {
						breaktime = 0;
						breakcylinder = current_cylinder;
						plan_add_segment(diveplan, clock - previous_point_time, depth, gas, po2, false);
						previous_point_time = clock;
						current_cylinder = 0;
						gas = displayed_dive.cylinder[current_cylinder].gasmix;
					}
				} else {
					if (breaktime >= 0) {
						breaktime += DECOTIMESTEP;
						if (breaktime >= 6 * 60) {
							o2time = 0;
							plan_add_segment(diveplan, clock - previous_point_time, depth, gas, po2, false);
							previous_point_time = clock;
							current_cylinder = breakcylinder;
							gas = displayed_dive.cylinder[current_cylinder].gasmix;
							breaktime = -1;
						}
					}
				}
			}
			trial_depth = depth;
		}
		if (stopping) {
			/* Next we will ascend again. Add a waypoint if we have spend deco time */
			plan_add_segment(diveplan, clock - previous_point_time, depth, gas, po2, false);
			previous_point_time = clock;
			stopping = false;
		}
	}

	/* We made it to the surface
	 * Create the final dive, add the plan to the notes and fixup some internal
	 * data that we need to be there when plotting the dive */
	plan_add_segment(diveplan, clock - previous_point_time, 0, gas, po2, false);
	create_dive_from_plan(diveplan, is_planner);
	add_plan_to_notes(diveplan, &displayed_dive, show_disclaimer, error);
	fixup_dc_duration(&displayed_dive.dc);

	free(stoplevels);
	free(gaschanges);
	return error;
}
Exemplo n.º 11
0
double VRP::RTR_solve(int heuristics, int intensity, int max_stuck, int max_perturbs,
                      double dev, int nlist_size, int perturb_type, int accept_type, bool verbose)
{
    ///
    /// Uses the given parameters to generate a 
    /// VRP solution via record-to-record travel.
    /// Assumes that data has already been imported into V and that we have
    /// some existing solution.
    /// Returns the objective function value of the best solution found
    ///

    // Make sure accept_type is either VRPH_BEST_ACCEPT or VRPH_FIRST_ACCEPT - matters only
    // for the downhill phase as we use VRPH_LI_ACCEPT in the diversification phase

    if(accept_type!=VRPH_BEST_ACCEPT && accept_type!=VRPH_FIRST_ACCEPT)
        report_error("%s: accept_type must be VRPH_BEST_ACCEPT or VRPH_FIRST_ACCEPT\n");

    int ctr, n, j,  i,  R, random, fixed, neighbor_list, objective, tabu;

    random=fixed=neighbor_list=0;

    if(heuristics & VRPH_RANDOMIZED)
        random=VRPH_RANDOMIZED;

    if(heuristics & VRPH_FIXED_EDGES)
        fixed=VRPH_FIXED_EDGES;

    if(heuristics & VRPH_USE_NEIGHBOR_LIST)
        neighbor_list=VRPH_USE_NEIGHBOR_LIST;

    objective=VRPH_SAVINGS_ONLY;
    // default strategy

    if(heuristics & VRPH_MINIMIZE_NUM_ROUTES)
        objective=VRPH_MINIMIZE_NUM_ROUTES;


    if(heuristics & VRPH_TABU)
    {
        tabu=VRPH_TABU; // We will use a primitive Tabu Search in the uphill phase
        // Clear the tabu list
        this->tabu_list->empty();
    }
    else
        tabu=0;

    n=num_nodes;

    // Define the heuristics we will use

    OnePointMove OPM;
    TwoPointMove TPM;
    TwoOpt         TO;
    OrOpt         OR;
    ThreeOpt     ThreeO;
    CrossExchange    CE;
    ThreePointMove ThreePM;

    double start_val;
    int *perm;
    perm=new int[this->num_nodes];


    j=VRPH_ABS(this->next_array[VRPH_DEPOT]);
    for(i=0;i<this->num_nodes;i++)
    {
        perm[i]=j;
        if(!routed[j])
            report_error("%s: Unrouted node in solution!!\n");

        j=VRPH_ABS(this->next_array[j]);
    }
    if(j!=VRPH_DEPOT)
        report_error("%s: VRPH_DEPOT is not last node in solution!!\n");


    int rules;

    // Set the neighbor list size used in the improvement search
    neighbor_list_size=VRPH_MIN(nlist_size, this->num_nodes);

    // Set the deviation
    deviation=dev;

    int num_perturbs=0;

    record=this->total_route_length;
    this->best_total_route_length=this->total_route_length;
    this->export_solution_buff(this->current_sol_buff);
    this->export_solution_buff(this->best_sol_buff);

    normalize_route_numbers();

    ctr=0;


uphill:
    // Start an uphill phase using the following "rules":
    double beginning_best=this->best_total_route_length;
    rules=VRPH_LI_ACCEPT+VRPH_RECORD_TO_RECORD+objective+random+fixed+neighbor_list+tabu;

    if(verbose)
        printf("Uphill starting at %5.2f\n",this->total_route_length);
    
    for(int k=1;k<intensity;k++)
    {
        start_val=total_route_length;

        if(heuristics & ONE_POINT_MOVE)
        {
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)
            {
#if FIXED_DEBUG
                if(fixed && !check_fixed_edges("Before 1PM\n"))
                    fprintf(stderr,"Error before OPM search(%d)\n",perm[i-1]);
#endif
                OPM.search(this,perm[i-1],rules);

#if FIXED_DEBUG
                if(fixed && !check_fixed_edges("After 1PM\n"))
                {
                    fprintf(stderr,"Error after OPM search(%d)\n",perm[i-1]);
                    this->show_route(this->route_num[perm[i-1]]);
                }
#endif
            }
        }


        if(heuristics & TWO_POINT_MOVE)
        {
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                TPM.search(this,perm[i-1],rules + VRPH_INTER_ROUTE_ONLY);

            //check_fixed_edges("After 2PM\n");

        }


        if(heuristics & THREE_POINT_MOVE)
        {
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                ThreePM.search(this,perm[i-1],rules + VRPH_INTER_ROUTE_ONLY);

            //check_fixed_edges("After 3PM\n");

        }



        if(heuristics & TWO_OPT)
        {
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                TO.search(this,perm[i-1],rules);

            //check_fixed_edges("After TO\n");


        }        


        if(heuristics & OR_OPT)
        {
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                OR.search(this,perm[i-1],4,rules);

            for(i=1;i<=n;i++)    
                OR.search(this,perm[i-1],3,rules);

            for(i=1;i<=n;i++)    
                OR.search(this,perm[i-1],2,rules);

            //check_fixed_edges("After OR\n");

        }

        if(heuristics & THREE_OPT)
        {
            normalize_route_numbers();
            R=total_number_of_routes;

            for(i=1; i<=R; i++)    
                ThreeO.route_search(this,i,rules-neighbor_list);

            //check_fixed_edges("After 3O\n");

        }

        if(heuristics & CROSS_EXCHANGE)
        {
            normalize_route_numbers();
            this->find_neighboring_routes();
            R=total_number_of_routes;

            for(i=1; i<=R-1; i++)    
            {
                for(j=0;j<1;j++)
                    CE.route_search(this,i, route[i].neighboring_routes[j],rules-neighbor_list); 
            }

            //check_fixed_edges("After CE\n");
        }
    }

    if(total_route_length<record)
        record = total_route_length;

    if(verbose)
    {
        printf("Uphill complete\t(%d,%5.2f,%5.2f)\n",count_num_routes(),total_route_length, record);
        printf("# of recorded routes: %d[%d]\n",total_number_of_routes,count_num_routes());

    }

    if(this->best_total_route_length<beginning_best-VRPH_EPSILON)
    {
        if(verbose)
            printf("New best found in uphill!\n");
        // We found a new best solution during the uphill phase that might
        // now be "forgotten"!! I have seen this happen where it is never recovered
        // again, so we just import it and start the downhill phase with this solution...
        //this->import_solution_buff(this->best_sol_buff);

    }

downhill:

    // Now enter a downhill phase
    double orig_val=total_route_length;
    if(verbose)
        printf("Downhill starting at %f (best=%f)\n",orig_val,this->best_total_route_length);


    if((heuristics & ONE_POINT_MOVE)|| (heuristics & KITCHEN_SINK) )
    {
        rules=VRPH_DOWNHILL+objective+random+fixed+neighbor_list+accept_type;
        for(;;)
        {
            // One Point Move
            start_val=total_route_length;

            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)
                OPM.search(this,perm[i-1],rules );


            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 

        }

    }



    if((heuristics & TWO_POINT_MOVE) || (heuristics & KITCHEN_SINK) )
    {
        rules=VRPH_DOWNHILL+VRPH_INTER_ROUTE_ONLY+objective+random+fixed+neighbor_list+accept_type;
        for(;;)
        {
            // Two Point Move
            start_val=total_route_length;

            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                TPM.search(this,perm[i-1],rules);

            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 

        }

    }



    if((heuristics & TWO_OPT)|| (heuristics & KITCHEN_SINK) )
    {
        // Do inter-route first a la Li
        rules=VRPH_DOWNHILL+VRPH_INTER_ROUTE_ONLY+objective+random+fixed+neighbor_list+accept_type;
        for(;;)
        {

            start_val=total_route_length;

            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                TO.search(this,perm[i-1],rules);

            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 
        }

        // Now do both intra and inter
        rules=VRPH_DOWNHILL+objective+random+fixed+neighbor_list+accept_type;

        for(;;)
        {

            start_val=total_route_length;

            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                TO.search(this,perm[i-1],rules);

            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 
        }
    }

    if((heuristics & THREE_POINT_MOVE) || (heuristics & KITCHEN_SINK) )
    {
        rules=VRPH_DOWNHILL+VRPH_INTER_ROUTE_ONLY+objective+random+fixed+accept_type+neighbor_list;
        for(;;)
        {
            // Three Point Move
            start_val=total_route_length;

            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                ThreePM.search(this,perm[i-1],rules);

            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 

        }
    }


    if((heuristics & OR_OPT) || (heuristics & KITCHEN_SINK))
    {

        rules=VRPH_DOWNHILL+ objective +random +fixed + accept_type + neighbor_list;

        for(;;)
        {
            // OrOpt
            start_val=total_route_length;
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                OR.search(this,perm[i-1],4,rules);
            for(i=1;i<=n;i++)
                OR.search(this,perm[i-1],3,rules);
            for(i=1;i<=n;i++)
                OR.search(this,perm[i-1],2,rules);


            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 
        }
    }

    if((heuristics & THREE_OPT) || (heuristics & KITCHEN_SINK) )
    {
        normalize_route_numbers();
        R= total_number_of_routes;
        rules=VRPH_DOWNHILL+objective+VRPH_INTRA_ROUTE_ONLY+ random +fixed + accept_type;
        for(;;)
        {
            // 3OPT
            start_val=total_route_length;

            for(i=1;i<=R;i++)    
                ThreeO.route_search(this,i,rules);

            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 
        }
    }


    if( (heuristics & CROSS_EXCHANGE) )
    {
        normalize_route_numbers();
        this->find_neighboring_routes();
        R=total_number_of_routes;

        rules=VRPH_DOWNHILL+objective+VRPH_INTRA_ROUTE_ONLY+ random +fixed + accept_type;

        for(i=1; i<=R-1; i++)    
        {
            for(j=0;j<=1;j++)
                CE.route_search(this,i, route[i].neighboring_routes[j], rules); 
        }
    }


    // Repeat the downhill phase until we find no more improvements
    if(total_route_length<orig_val-VRPH_EPSILON)
        goto downhill;
    if(verbose)
        printf("Downhill complete: %5.2f[downhill started at %f] (%5.2f)\n",total_route_length,orig_val,
        this->best_total_route_length);


    if(total_route_length < record-VRPH_EPSILON)    
    {
        // New record - reset ctr
        ctr=1;
        record=total_route_length;
    }
    else
        ctr++;

    if(ctr<max_stuck)
        goto uphill;

    if(ctr==max_stuck)
    {
        if(num_perturbs<max_perturbs)
        {
            if(verbose)
                printf("perturbing\n");
            if(perturb_type==VRPH_LI_PERTURB)
                perturb();
            else
                osman_perturb(VRPH_MAX(20,num_nodes/10),.5+lcgrand(20));

            // Reset record
            this->record=this->total_route_length;
            if(tabu)
                this->tabu_list->empty();

            ctr=1;
            num_perturbs++;
            goto uphill;
        }
    }


    if(verbose)
    {
        if(has_service_times==false)
            printf("BEST OBJ:  %f\n",best_total_route_length);
        else
            printf("BEST OBJ:  %f\n",best_total_route_length-total_service_time);
    }

    delete [] perm; 

    // Import the best solution found
    this->import_solution_buff(best_sol_buff);

    if(has_service_times==false)
        return best_total_route_length;
    else
        return best_total_route_length-total_service_time;


}
Exemplo n.º 12
0
/* simply overwrite the data in the displayed_dive
 * return false if something goes wrong */
static void create_dive_from_plan(struct diveplan *diveplan, bool track_gas)
{
	struct divedatapoint *dp;
	struct divecomputer *dc;
	struct sample *sample;
	struct gasmix oldgasmix;
	struct event *ev;
	cylinder_t *cyl;
	int oldpo2 = 0;
	int lasttime = 0;
	int lastdepth = 0;

	if (!diveplan || !diveplan->dp)
		return;
#if DEBUG_PLAN & 4
	printf("in create_dive_from_plan\n");
	dump_plan(diveplan);
#endif
	// reset the cylinders and clear out the samples and events of the
	// displayed dive so we can restart
	reset_cylinders(&displayed_dive, track_gas);
	dc = &displayed_dive.dc;
	dc->when = displayed_dive.when = diveplan->when;
	free(dc->sample);
	dc->sample = NULL;
	dc->samples = 0;
	dc->alloc_samples = 0;
	while ((ev = dc->events)) {
		dc->events = dc->events->next;
		free(ev);
	}
	dp = diveplan->dp;
	cyl = &displayed_dive.cylinder[0];
	oldgasmix = cyl->gasmix;
	sample = prepare_sample(dc);
	sample->po2.mbar = dp->po2;
	if (track_gas && cyl->type.workingpressure.mbar)
		sample->cylinderpressure.mbar = cyl->end.mbar;
	sample->manually_entered = true;
	finish_sample(dc);
	while (dp) {
		struct gasmix gasmix = dp->gasmix;
		int po2 = dp->po2;
		int time = dp->time;
		int depth = dp->depth;

		if (time == 0) {
			/* special entries that just inform the algorithm about
			 * additional gases that are available */
			if (verify_gas_exists(gasmix) < 0)
				goto gas_error_exit;
			dp = dp->next;
			continue;
		}

		/* Check for SetPoint change */
		if (oldpo2 != po2) {
			if (lasttime)
				/* this is a bad idea - we should get a different SAMPLE_EVENT type
				 * reserved for this in libdivecomputer... overloading SMAPLE_EVENT_PO2
				 * with a different meaning will only cause confusion elsewhere in the code */
				add_event(dc, lasttime, SAMPLE_EVENT_PO2, 0, po2, "SP change");
			oldpo2 = po2;
		}

		/* Make sure we have the new gas, and create a gas change event */
		if (gasmix_distance(&gasmix, &oldgasmix) > 0) {
			int idx;
			if ((idx = verify_gas_exists(gasmix)) < 0)
				goto gas_error_exit;
			/* need to insert a first sample for the new gas */
			add_gas_switch_event(&displayed_dive, dc, lasttime + 1, idx);
			cyl = &displayed_dive.cylinder[idx];
			sample = prepare_sample(dc);
			sample[-1].po2.mbar = po2;
			sample->time.seconds = lasttime + 1;
			sample->depth.mm = lastdepth;
			sample->manually_entered = dp->entered;
			if (track_gas && cyl->type.workingpressure.mbar)
				sample->cylinderpressure.mbar = cyl->sample_end.mbar;
			finish_sample(dc);
			oldgasmix = gasmix;
		}
		/* Create sample */
		sample = prepare_sample(dc);
		/* set po2 at beginning of this segment */
		/* and keep it valid for last sample - where it likely doesn't matter */
		sample[-1].po2.mbar = po2;
		sample->po2.mbar = po2;
		sample->time.seconds = lasttime = time;
		sample->depth.mm = lastdepth = depth;
		sample->manually_entered = dp->entered;
		if (track_gas) {
			update_cylinder_pressure(&displayed_dive, sample[-1].depth.mm, depth, time - sample[-1].time.seconds,
					dp->entered ? diveplan->bottomsac : diveplan->decosac, cyl, !dp->entered);
			if (cyl->type.workingpressure.mbar)
				sample->cylinderpressure.mbar = cyl->end.mbar;
		}
		finish_sample(dc);
		dp = dp->next;
	}
#if DEBUG_PLAN & 32
	save_dive(stdout, &displayed_dive);
#endif
	return;

gas_error_exit:
	report_error(translate("gettextFromC", "Too many gas mixes"));
	return;
}
Exemplo n.º 13
0
static void go(char *lang1, char *lang2,
               char *lexfile1, char *dicfile1,
               char *lexfile2, char *dicfile2,
               char *outfile) {
    Words *lex1, *lex2;
    wchar_t *string1 = NULL;
    wchar_t *string2 = NULL;
    nat_uint32_t ptr1 = 0;
    nat_uint32_t ptr2 = 0;
    nat_uint32_t size1, size2;
    NATCell *cells1 = NULL;
    NATCell *cells2 = NULL;
    nat_uint32_t cellptr1 = 0;
    nat_uint32_t cellptr2 = 0;
    nat_uint32_t *tab1 = NULL;
    nat_uint32_t *tab2 = NULL;

    /* ---- First ------------------------------- */
    lex1 = words_quick_load(lexfile1);
    if (!lex1) { fprintf(stderr, "Error loading lexicon 1\n"); exit(1); }

    size1 = 11 * lex1->count;

    string1 = g_new0(wchar_t, size1);
    if (!string1) { fprintf(stderr, "Error allocating string1\n"); exit(1); }

    cells1 = g_new0(NATCell, lex1->count + 1);
    if (!cells1) { fprintf(stderr, "Error allocating cells1\n"); exit(1); }

    tab1 = g_new0(nat_uint32_t, lex1->count + 1);
    if (!tab1) { fprintf(stderr, "Error allocating tab1\n"); exit(1); }

    tab1[0] = tab1[1] = lex1->count-1;
    ptr1 = tree_to_array(lex1->count,string1, cells1, lex1->tree, ptr1, size1, &cellptr1, tab1);
    
    cells1[cellptr1].offset = ptr1;
    cells1[cellptr1].count = 0;
    cells1[cellptr1].id = cellptr1;
    cellptr1++;

    g_message("** Preparing source Lexicon **");
    g_message("\tPtr is at %u and original size was %u", ptr1, size1);
    g_message("\tOffset on the array is %u", cellptr1);
    g_message("\tNULL is pointing to %u", tab1[0]);

    /* ---- Second ------------------------------ */
    lex2 = words_quick_load(lexfile2);
    if (!lex2) report_error("Error loading lexicon 2\n");

    size2 = 11*lex2->count;

    string2 = g_new0(wchar_t, size2);
    if (!string2) report_error("Error allocating string2\n");

    cells2 = g_new0(NATCell, lex2->count+1);
    if (!cells2) report_error("Error allocating cells2\n");

    tab2 = g_new0(nat_uint32_t, lex2->count+1);
    if (!tab2) report_error("Error allocating tab2\n");

    tab2[0] = tab2[1] = lex2->count-1;
    ptr2 = tree_to_array(lex2->count,string2, cells2, lex2->tree, ptr2, size2, &cellptr2, tab2);

    cells2[cellptr2].offset = ptr2;
    cells2[cellptr2].count = 0;
    cells2[cellptr2].id = cellptr2;
    cellptr2++;

    g_message("** Preparing target Lexicon **");
    g_message("\tPtr is at %u and original size was %u", ptr2, size2);
    g_message("\tOffset on the array is %u", cellptr2);
    g_message("\tNULL is pointing to %u", tab2[0]);

    save(outfile,
	 lang1, lang2, 
	 dicfile1, tab1, dicfile2, tab2,
	 string1, ptr1, cells1, cellptr1,
	 string2, ptr2, cells2, cellptr2);   

/*    save(outfile, lang1, lang2, 
	 dicfile1, tab1, dicfile2, tab2,
	 string1, ptr1, cells1, lex1->count,
	 string2, ptr2, cells2, lex2->count);   */


    words_free(lex1);
    words_free(lex2);
}
Exemplo n.º 14
0
void lr_parser::syntax_error(lr_symbol* cur_token)
{
  report_error("Syntax error", cur_token);
}
Exemplo n.º 15
0
int solve(clingo_control_t *ctl) {
    clingo_solve_result_t ret;
    if (report_error(clingo_control_solve(ctl, 0, &on_model, 0, &ret))) { return 0; }
    printf("the solve result is: %d\n", ret);
    return 1;
}
Exemplo n.º 16
0
void PreferencesNetwork::syncSettings()
{
	auto cloud = qPrefCloudStorage::instance();
	auto proxy = qPrefProxy::instance();

	proxy->set_proxy_type(ui->proxyType->itemData(ui->proxyType->currentIndex()).toInt());
	proxy->set_proxy_host(ui->proxyHost->text());
	proxy->set_proxy_port(ui->proxyPort->value());
	proxy->set_proxy_auth(ui->proxyAuthRequired->isChecked());
	proxy->set_proxy_user(ui->proxyUsername->text());
	proxy->set_proxy_pass(ui->proxyPassword->text());

	QString email = ui->cloud_storage_email->text();
	QString password = ui->cloud_storage_password->text();
	QString newpassword = ui->cloud_storage_new_passwd->text();

	//TODO: Change this to the Cloud Storage Stuff, not preferences.
	if (prefs.cloud_verification_status == qPref::CS_VERIFIED && !newpassword.isEmpty()) {
		// deal with password change
		if (!email.isEmpty() && !password.isEmpty()) {
			// connect to backend server to check / create credentials
			QRegularExpression reg("^[a-zA-Z0-9@.+_-]+$");
			if (!reg.match(email).hasMatch() || (!password.isEmpty() && !reg.match(password).hasMatch())) {
				report_error(qPrintable(tr("Change ignored. Cloud storage email and password can only consist of letters, numbers, and '.', '-', '_', and '+'.")));
				return;
			}
			if (!reg.match(email).hasMatch() || (!newpassword.isEmpty() && !reg.match(newpassword).hasMatch())) {
				report_error(qPrintable(tr("Change ignored. Cloud storage email and new password can only consist of letters, numbers, and '.', '-', '_', and '+'.")));
				ui->cloud_storage_new_passwd->setText("");
				return;
			}
			CloudStorageAuthenticate *cloudAuth = new CloudStorageAuthenticate(this);
			connect(cloudAuth, &CloudStorageAuthenticate::finishedAuthenticate, this, &PreferencesNetwork::updateCloudAuthenticationState);
			connect(cloudAuth, &CloudStorageAuthenticate::passwordChangeSuccessful, this, &PreferencesNetwork::passwordUpdateSuccessful);
			cloudAuth->backend(email, password, "", newpassword);
			ui->cloud_storage_new_passwd->setText("");
		}
	} else if (prefs.cloud_verification_status == qPref::CS_UNKNOWN ||
		   prefs.cloud_verification_status == qPref::CS_INCORRECT_USER_PASSWD ||
		   email != prefs.cloud_storage_email ||
		   password != prefs.cloud_storage_password) {

		// different credentials - reset verification status
		int oldVerificationStatus = cloud->cloud_verification_status();
		cloud->set_cloud_verification_status(qPref::CS_UNKNOWN);
		if (!email.isEmpty() && !password.isEmpty()) {
			// connect to backend server to check / create credentials
			QRegularExpression reg("^[a-zA-Z0-9@.+_-]+$");
			if (!reg.match(email).hasMatch() || (!password.isEmpty() && !reg.match(password).hasMatch())) {
				report_error(qPrintable(tr("Cloud storage email and password can only consist of letters, numbers, and '.', '-', '_', and '+'.")));
				cloud->set_cloud_verification_status(oldVerificationStatus);
				return;
			}
			CloudStorageAuthenticate *cloudAuth = new CloudStorageAuthenticate(this);
			connect(cloudAuth, &CloudStorageAuthenticate::finishedAuthenticate, this, &PreferencesNetwork::updateCloudAuthenticationState);
			cloudAuth->backend(email, password);
		}
	} else if (prefs.cloud_verification_status == qPref::CS_NEED_TO_VERIFY) {
		QString pin = ui->cloud_storage_pin->text();
		if (!pin.isEmpty()) {
			// connect to backend server to check / create credentials
			QRegularExpression reg("^[a-zA-Z0-9@.+_-]+$");
			if (!reg.match(email).hasMatch() || !reg.match(password).hasMatch()) {
				report_error(qPrintable(tr("Cloud storage email and password can only consist of letters, numbers, and '.', '-', '_', and '+'.")));
				return;
			}
			CloudStorageAuthenticate *cloudAuth = new CloudStorageAuthenticate(this);
			connect(cloudAuth, SIGNAL(finishedAuthenticate()), this, SLOT(updateCloudAuthenticationState()));
			cloudAuth->backend(email, password, pin);
		}
	}
	cloud->set_cloud_storage_email(email);
	cloud->set_save_password_local(ui->save_password_local->isChecked());
	cloud->set_cloud_storage_password(password);
	cloud->set_cloud_verification_status(prefs.cloud_verification_status);
	cloud->set_cloud_base_url(prefs.cloud_base_url);
}
Exemplo n.º 17
0
int main(int argc, char **argv)
{
  int ret;
  int p, ts;
  int var;
  int slice = 0;
  int nprocs = 1, rank = 0;
  char output_file_name[512];

  // MPI initialization
#if PIDX_HAVE_MPI
  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif

  if (rank == 0)
  {
    ret = parse_args(argc, argv);
    if (ret < 0)
    {
      usage();
#if PIDX_HAVE_MPI
      MPI_Abort(MPI_COMM_WORLD, -1);
#else
      exit(-1);
#endif
    }

    // check if the num procs is appropriate
    int num_bricks = (global_box_size[0] / local_box_size[0]) * (global_box_size[1] / local_box_size[1]) * (global_box_size[2] / local_box_size[2]);
    if(num_bricks != nprocs)
    {
      fprintf(stderr, "Error: number of sub-blocks (%d) doesn't match number of procs (%d)\n", num_bricks, nprocs);
      fprintf(stderr, "Incorrect distribution of data across processes i.e.\n(global_x / local_x) X (global_x / local_x) X (global_x / local_x) != nprocs\n(%d/%d) X (%d/%d) X (%d/%d) != %d\n", global_box_size[0], local_box_size[0], global_box_size[1], local_box_size[1], global_box_size[2], local_box_size[2], nprocs);

#if PIDX_HAVE_MPI
      MPI_Abort(MPI_COMM_WORLD, -1);
#else
      exit(-1);
#endif
    }
  }

#if 1
  //  The command line arguments are shared by all processes
#if PIDX_HAVE_MPI
  MPI_Bcast(global_box_size, 3, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(local_box_size, 3, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&time_step_count, 1, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&variable_count, 1, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&patch_count, 1, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&output_file_template, 512, MPI_CHAR, 0, MPI_COMM_WORLD);
  MPI_Bcast(&blocks_per_file, 1, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&bits_per_block, 1, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(restructured_box_size, 5, MPI_LONG_LONG, 0, MPI_COMM_WORLD);
  MPI_Bcast(&compression_type, 1, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&compression_bit_rate, 1, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(perform_phases, 6, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(debug_rst_hz, 2, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(dump_agg_io, 2, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(idx_count, 3, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&aggregation_factor, 1, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&is_rank_z_ordering, 1, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(hz_from_to, 2, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(rst_agg, 2, MPI_INT, 0, MPI_COMM_WORLD);
#endif

  values_per_sample = malloc(sizeof(*values_per_sample) * variable_count);
  memset(values_per_sample, 0, sizeof(*values_per_sample) * variable_count);

  // Creating the filename
  sprintf(output_file_name, "%s%s", output_file_template,".idx");

  // Calculating every process data's offset and size
  int sub_div[3];
  sub_div[0] = (global_box_size[0] / local_box_size[0]);
  sub_div[1] = (global_box_size[1] / local_box_size[1]);
  sub_div[2] = (global_box_size[2] / local_box_size[2]);
  local_box_offset[2] = (rank / (sub_div[0] * sub_div[1])) * local_box_size[2];
  slice = rank % (sub_div[0] * sub_div[1]);
  local_box_offset[1] = (slice / sub_div[0]) * local_box_size[1];
  local_box_offset[0] = (slice % sub_div[0]) * local_box_size[0];

  unsigned int rank_x = 0, rank_y = 0, rank_z = 0, rank_slice;
  if (is_rank_z_ordering == 0)
  {
    rank_z = rank / (sub_div[0] * sub_div[1]);
    rank_slice = rank % (sub_div[0] * sub_div[1]);
    rank_y = (rank_slice / sub_div[0]);
    rank_x = (rank_slice % sub_div[0]);
  }

  create_patches();

  PIDX_file file;            // IDX file descriptor
  PIDX_variable* variable;   // variable descriptor

  variable = malloc(sizeof(*variable) * variable_count);
  memset(variable, 0, sizeof(*variable) * variable_count);

  PIDX_point global_bounding_box, **local_offset_point, **local_box_count_point;

  local_offset_point = malloc(sizeof(PIDX_point*) * variable_count);
  local_box_count_point = malloc(sizeof(PIDX_point*) * variable_count);
  for(var = 0; var < variable_count; var++)
  {
    local_offset_point[var] = malloc(sizeof(PIDX_point) * patch_count);
    local_box_count_point[var] = malloc(sizeof(PIDX_point) * patch_count);
    for(p = 0 ; p < patch_count ; p++)
    {
      PIDX_set_point_5D(local_offset_point[var][p], (int64_t)local_patch_offset[var][p][0], (int64_t)local_patch_offset[var][p][1], (int64_t)local_patch_offset[var][p][2], 0, 0);
      PIDX_set_point_5D(local_box_count_point[var][p], (int64_t)local_patch_size[var][p][0], (int64_t)local_patch_size[var][p][1], (int64_t)local_patch_size[var][p][2], 1, 1);
    }
  }
  PIDX_set_point_5D(global_bounding_box, (int64_t)global_box_size[0], (int64_t)global_box_size[1], (int64_t)global_box_size[2], 1, 1);

  PIDX_access access;
  PIDX_create_access(&access);

#if PIDX_HAVE_MPI
  PIDX_set_mpi_access(access, MPI_COMM_WORLD);
  PIDX_set_idx_count(access, idx_count[0], idx_count[1], idx_count[2]);
  PIDX_set_process_extent(access, sub_div[0], sub_div[1], sub_div[2]);
  PIDX_set_process_rank_decomposition(access, rank_x, rank_y, rank_z);
#endif

  for (ts = 0; ts < time_step_count; ts++)
  {
    PIDX_file_create(output_file_name, PIDX_MODE_CREATE, access, &file);
    PIDX_set_dims(file, global_bounding_box);
    PIDX_set_current_time_step(file, ts);
    PIDX_set_variable_count(file, variable_count);

    PIDX_set_resolution(file, hz_from_to[0], hz_from_to[1]);
    PIDX_set_block_size(file, bits_per_block);
    PIDX_set_block_count(file, blocks_per_file);

    // PIDX set restructuring box size
    PIDX_set_restructuring_box(file, restructured_box_size);

    // PIDX compression related calls
    if (compression_type == 0)
      PIDX_set_compression_type(file, PIDX_NO_COMPRESSION);
    if (compression_type == 1)
      PIDX_set_compression_type(file, PIDX_CHUNKING_ONLY);
    if (compression_type == 2)
    {
      PIDX_set_compression_type(file, PIDX_CHUNKING_ZFP);
      PIDX_set_lossy_compression_bit_rate(file, compression_bit_rate);
    }

    PIDX_debug_rst(file, debug_rst_hz[0]);
    PIDX_debug_hz(file, debug_rst_hz[1]);
    PIDX_dump_agg_info(file, dump_agg_io[0]);
    PIDX_dump_io_info(file, dump_agg_io[1]);

    if (perform_phases[0] == 0)
      PIDX_debug_disable_restructuring(file);
    if (perform_phases[1] == 0)
      PIDX_debug_disable_chunking(file);
    if (perform_phases[2] == 0)
      PIDX_debug_disable_hz(file);
    if (perform_phases[3] == 0)
      PIDX_debug_disable_compression(file);
    if (perform_phases[4] == 0)
      PIDX_debug_disable_agg(file);
    if (perform_phases[5] == 0)
      PIDX_debug_disable_io(file);

    if (rst_agg[0] == 0)
      PIDX_disable_rst(file);
    if (rst_agg[1] == 0)
      PIDX_disable_agg(file);

    for (var = 0; var < variable_count; var++)
    {
      char variable_name[512];
      char data_type[512];
      sprintf(variable_name, "variable_%d", var);
      sprintf(data_type, "%d*float64", values_per_sample[var]);

      ret = PIDX_variable_create(variable_name, sizeof(double) * 8, data_type, &variable[var]);
      if (ret != PIDX_success)  report_error("PIDX_variable_create", __FILE__, __LINE__);

      for (p = 0 ; p < patch_count ; p++)
      {
        ret = PIDX_variable_write_data_layout(variable[var], local_offset_point[var][p], local_box_count_point[var][p], NULL, PIDX_row_major);
        if (ret != PIDX_success)  report_error("PIDX_variable_data_layout", __FILE__, __LINE__);
      }

      ret = PIDX_append_and_write_variable(file, variable[var]);
      if (ret != PIDX_success)  report_error("PIDX_append_and_write_variable", __FILE__, __LINE__);

      ret = PIDX_flush(file);
    }
    ret = PIDX_close(file);
    if (ret != PIDX_success)  report_error("PIDX_close", __FILE__, __LINE__);
  }
  PIDX_close_access(access);

  for(var = 0; var < variable_count; var++)
  {
    free(local_offset_point[var]);
    free(local_box_count_point[var]);
  }
  free(local_offset_point);
  free(local_box_count_point);

  free(variable);
  variable = 0;
  free(values_per_sample);
  values_per_sample = 0;

  destroy_patches();
#endif

#if PIDX_HAVE_MPI
  MPI_Finalize();
#endif

  return 0;
}
Exemplo n.º 18
0
 void SSS::handle_error(const std::string & msg, double x)const{
   report_error(msg + " in ScalarSliceSampler" +
                error_message(lo_, hi_, x, logplo_, logphi_, logp_slice_));
 }
Exemplo n.º 19
0
/*! \brief
 * Checks the validity of selection method callback functions.
 *
 * \param[in] fp        File handle to use for diagnostic messages
 *   (can be NULL).
 * \param[in] method    The method to check.
 * \returns   true if there are no problems, false otherwise.
 *
 * This function performs some checks common to both check_method() and
 * check_modifier().
 * This function checks that all the required callbacks are defined, i.e.,
 * not NULL, to find programming errors.
 */
static bool
check_callbacks(FILE *fp, gmx_ana_selmethod_t *method)
{
    bool         bOk = true;
    bool         bNeedInit;
    int          i;

    /* Make some checks on init_data and free */
    if (method->nparams > 0 && !method->init_data)
    {
        report_error(fp, method->name, "error: init_data should be provided because the method has parameters");
        bOk = false;
    }
    if (method->free && !method->init_data)
    {
        report_error(fp, method->name, "warning: free is not used because of missing init_data");
    }
    /* Check presence of outinit for position-valued methods */
    if (method->type == POS_VALUE && !method->outinit)
    {
        report_error(fp, method->name, "error: outinit should be provided because the method has POS_VALUE");
        bOk = false;
    }
    /* Check presence of outinit for variable output count methods */
    if ((method->flags & SMETH_VARNUMVAL) && !method->outinit)
    {
        report_error(fp, method->name, "error: outinit should be provided because the method has SMETH_VARNUMVAL");
        bOk = false;
    }
    /* Warn of dynamic callbacks in static methods */
    if (!(method->flags & SMETH_MODIFIER))
    {
        if (method->pupdate && !(method->flags & SMETH_DYNAMIC))
        {
            report_error(fp, method->name, "warning: pupdate not used because the method is static");
            method->pupdate = NULL;
        }
    }
    /* Check that there is an evaluation function */
    if (method->type != NO_VALUE && !method->update && !method->pupdate)
    {
        report_error(fp, method->name, "error: evaluation function missing");
        bOk = false;
    }
    /* Loop through the parameters to determine if initialization callbacks
     * are needed. */
    bNeedInit = false;
    for (i = 0; i < method->nparams; ++i)
    {
        if (method->param[i].val.type != POS_VALUE
            && (method->param[i].flags & (SPAR_VARNUM | SPAR_ATOMVAL)))
        {
            bNeedInit = true;
        }
    }
    /* Check that the callbacks required by the parameters are present */
    if (bNeedInit && !method->init)
    {
        report_error(fp, method->name, "error: init should be provided");
        bOk = false;
    }
    return bOk;
}
Exemplo n.º 20
0
QMutexPrivate::QMutexPrivate(QMutex::RecursionMode mode)
    : lock(0), owner(0), count(0), recursive(mode == QMutex::Recursive), wakeup(false)
{
    report_error(pthread_mutex_init(&mutex, NULL), "QMutex", "mutex init");
    report_error(pthread_cond_init(&cond, NULL), "QMutex", "cv init");
}
Exemplo n.º 21
0
bool SwapEnds::evaluate(class VRP *V, int a, int v, VRPMove *M)
{

    ///
    /// This function takes the routes containing nodes a and v
    /// and evaluates the swapping of the ends of the routes following a and v respectively,
    /// subject to the provided rules.
    /// Example:  VRPH_DEPOT-i-a-j-k-l-VRPH_DEPOT and VRPH_DEPOT-t-u-v-x-y-z-VRPH_DEPOT becomes
    /// VRPH_DEPOT-i-a-x-y-z-VRPH_DEPOT and VRPH_DEPOT-t-u-v-j-k-l-VRPH_DEPOT
    ///

    
    int load_after_a, load_after_v, new_a_load, new_v_load, added_to_a, added_to_v, n, b, w;
    double new_a_len, new_v_len ;
    double savings;
    VRPSegment Sa, Sv;


    if(a==VRPH_DEPOT || v==VRPH_DEPOT)
        report_error("%s: Swap ends called with depot; Move doesn't make sense\n",__FUNCTION__);

    n = V->num_nodes;
    

    if(V->route_num[a] == V->route_num[v])
    {
        fprintf(stderr,"a=%d; v=%d; %d==%d!!\n",a,v,V->route_num[a], V->route_num[v]);
        report_error("%s: swap ends called with a and v in same route!\n",__FUNCTION__);
    }
    
    w = VRPH_MAX(V->next_array[v],0);
    b = VRPH_MAX(V->next_array[a],0);
    
    savings = ((V->d[a][w] + V->d[v][b]) - (V->d[a][b] + V->d[v][w]));
    
    V->get_segment_info(VRPH_DEPOT, a, &Sa);
    added_to_v= V->route[V->route_num[a]].num_customers-Sa.num_custs;

    load_after_a = V->route[V->route_num[a]].load - Sa.load;

    V->get_segment_info(VRPH_DEPOT, v, &Sv);
    added_to_a=V->route[V->route_num[v]].num_customers-Sv.num_custs;

    load_after_v = V->route[V->route_num[v]].load - Sv.load;
    
    
    /// Example: ( a & v input): VRPH_DEPOT-i-a-b-j-k-l-VRPH_DEPOT and VRPH_DEPOT-t-u-v-w-x-y-z-VRPH_DEPOT becomes
    /// VRPH_DEPOT-i-a-w-x-y-z-VRPH_DEPOT and VRPH_DEPOT-t-u-v-b-j-k-l-VRPH_DEPOT

    new_a_len = Sa.len + V->route[V->route_num[v]].length - Sv.len + V->d[a][w]-V->d[v][w];
    new_a_load = Sa.load + load_after_v;
    new_v_len = Sv.len + V->route[V->route_num[a]].length - Sa.len  + V->d[v][b]-V->d[a][b];
    new_v_load = Sv.load + load_after_a;

    if(new_a_len > V->max_route_length || new_v_len > V->max_route_length 
        || new_a_load > V->max_veh_capacity || new_v_load > V->max_veh_capacity )
        // We violate some capacity constraint & the move is infeasible
        return false;


    // else the move is feasible and meets rules - record the move;

    M->num_affected_routes=2;
    M->route_nums[0]=V->route_num[a];
    M->route_nums[1]=V->route_num[v];
    M->savings=savings;
    M->route_lens[0]=new_a_len;
    M->route_lens[1]=new_v_len;
    M->route_loads[0]=new_a_load;
    M->route_loads[1]=new_v_load;
    M->route_custs[0]=V->route[V->route_num[a]].num_customers-added_to_v+added_to_a;
    M->route_custs[1]=V->route[V->route_num[v]].num_customers-added_to_a+added_to_v;
    M->new_total_route_length= V->total_route_length+M->savings;
    M->total_number_of_routes=V->total_number_of_routes;//none destroyed here
    M->move_type=SWAP_ENDS;
    M->num_arguments=2;
    M->move_arguments[0]=a;
    M->move_arguments[1]=v;
    

    return true;    
    
}
Exemplo n.º 22
0
QMutexPrivate::~QMutexPrivate()
{
    report_error(pthread_cond_destroy(&cond), "QMutex", "cv destroy");
    report_error(pthread_mutex_destroy(&mutex), "QMutex", "mutex destroy");
}
Exemplo n.º 23
0
int main(int argc, char* argv[]){
    SSL *ssl_connection = NULL;
    const char *host = NULL, *port = NULL;
    const char *username = NULL;
    char *response = NULL;
    char *signed_data_buffer = NULL;
    unsigned int signed_data_buffer_size = 0;
    RSA *my_rsa_key = NULL;
    
    if (argc != 3){
	fprintf(stderr, "Usage: %s host port.\n", argv[0]);
	exit(EXIT_FAILURE);
    }

    w_memory_init();
    openssl_init();
    
    host = argv[1];
    port = argv[2];
    username = getUsername();
    
    if (username == NULL)
	report_error_q("Unable to determine the username of this process.", __FILE__, __LINE__, 0);
 
    if((ssl_connection = ssl_client_connect(host, port)) == NULL)
	report_error_q(ERR_error_string(ERR_get_error(), NULL), __FILE__, __LINE__, 0);
    
    if (haveServerKey(host, username) == 0){
	ssl_write_uint(ssl_connection, REQUEST_KEY_AUTH);
	ssl_write_string(ssl_connection, username);
	my_rsa_key = getServerKey(host, username);
	if (my_rsa_key == NULL)
	    report_error_q("Key file exists, but data is invalid", __FILE__, __LINE__, 0);
    
    
	signed_data_buffer = (char *)w_malloc(key_buffer_size(my_rsa_key));
	signed_data_buffer_size = key_sign_data(my_rsa_key, username, strlen(username), signed_data_buffer, key_buffer_size(my_rsa_key));
	ssl_write_uint(ssl_connection, signed_data_buffer_size);
    
	ssl_write_bytes(ssl_connection, signed_data_buffer, signed_data_buffer_size);
    
	if (ssl_read_uint(ssl_connection) == SERVER_AUTH_SUCCESS){
	    printf("Server responded with SERVER_AUTH_SUCCESS.\n");
	}
	else {
	    printf("Server responded with SERVER_AUTH_SUCCESS.\n");
	}
	w_free(response);
    }
    else {
	ssl_write_uint(ssl_connection, REQUEST_PASS_AUTH);
	ssl_write_string(ssl_connection, username);
	ssl_write_string(ssl_connection, getUserPassword());
	
	if (ssl_read_uint(ssl_connection) == SERVER_AUTH_SUCCESS){
	    printf("Server reponded with SERVER_AUTH_SUCCESS, sending PKI Key.\n");
	    my_rsa_key = key_create_key();
	    if (!my_rsa_key){
		report_error("Error creating RSA key.", __FILE__, __LINE__, 0);
	    }
	    key_net_write_pub(my_rsa_key, ssl_connection);
	    writePrivKey(host, username, my_rsa_key);
	}
	else printf("Server responded with SERVER_AUTH_FAILURE.\n");
    }

    SSL_shutdown(ssl_connection);
    SSL_free(ssl_connection);
    return 0;
}
Exemplo n.º 24
0
void ReverseGeoLookupThread::run() {
	if (geo_lookup_data.isEmpty())
		return;

	QNetworkRequest request;
	QNetworkAccessManager *rgl = new QNetworkAccessManager();
	QEventLoop loop;
	QString mapquestURL("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=%1&lat=%2&lon=%3");
	QString geonamesURL("http://api.geonames.org/findNearbyPlaceNameJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh");
	QString geonamesOceanURL("http://api.geonames.org/oceanJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh");
	QString divelogsURL("https://www.divelogs.de/mapsearch_divespotnames.php?lat=%1&lng=%2&radius=50");
	QTimer timer;

	request.setRawHeader("Accept", "text/json");
	request.setRawHeader("User-Agent", getUserAgent().toUtf8());
	connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));

	Q_FOREACH (const GeoLookupInfo& info, geo_lookup_data ) {
		struct dive_site *ds = info.uuid ? get_dive_site_by_uuid(info.uuid) : &displayed_dive_site;

		// first check the findNearbyPlaces API from geonames - that should give us country, state, city
		request.setUrl(geonamesURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));

		QNetworkReply *reply = rgl->get(request);
		timer.setSingleShot(true);
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		timer.start(5000);   // 5 secs. timeout
		loop.exec();

		if(timer.isActive()) {
			timer.stop();
			if(reply->error() > 0) {
				report_error("got error accessing geonames.org: %s", qPrintable(reply->errorString()));
				goto clear_reply;
			}
			int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			if (v < 200 || v >= 300)
				goto clear_reply;
			QByteArray fullReply = reply->readAll();
			QJsonParseError errorObject;
			QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject);
			if (errorObject.error != QJsonParseError::NoError) {
				report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString()));
				goto clear_reply;
			}
			QJsonObject obj = jsonDoc.object();
			QVariant geoNamesObject = obj.value("geonames").toVariant();
			QVariantList geoNames = geoNamesObject.toList();
			if (geoNames.count() > 0) {
				QVariantMap firstData = geoNames.at(0).toMap();
				int ri = 0, l3 = -1, lt = -1;
				if (ds->taxonomy.category == NULL) {
					ds->taxonomy.category = alloc_taxonomy();
				} else {
					// clear out the data (except for the ocean data)
					int ocean;
					if ((ocean = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN)) > 0) {
						ds->taxonomy.category[0] = ds->taxonomy.category[ocean];
						ds->taxonomy.nr = 1;
					} else {
						// ocean is -1 if there is no such entry, and we didn't copy above
						// if ocean is 0, so the following gets us the correct count
						ds->taxonomy.nr = ocean + 1;
					}
				}
				// get all the data - OCEAN is special, so start at COUNTRY
				for (int j = TC_COUNTRY; j < TC_NR_CATEGORIES; j++) {
					if (firstData[taxonomy_api_names[j]].isValid()) {
						ds->taxonomy.category[ri].category = j;
						ds->taxonomy.category[ri].origin = taxonomy::GEOCODED;
						free((void*)ds->taxonomy.category[ri].value);
						ds->taxonomy.category[ri].value = copy_string(qPrintable(firstData[taxonomy_api_names[j]].toString()));
						ri++;
					}
				}
				ds->taxonomy.nr = ri;
				l3 = taxonomy_index_for_category(&ds->taxonomy, TC_ADMIN_L3);
				lt = taxonomy_index_for_category(&ds->taxonomy, TC_LOCALNAME);
				if (l3 == -1 && lt != -1) {
					// basically this means we did get a local name (what we call town), but just like most places
					// we didn't get an adminName_3 - which in some regions is the actual city that town belongs to,
					// then we copy the town into the city
					ds->taxonomy.category[ri].value = copy_string(ds->taxonomy.category[lt].value);
					ds->taxonomy.category[ri].origin = taxonomy::COPIED;
					ds->taxonomy.category[ri].category = TC_ADMIN_L3;
					ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			} else {
				report_error("geonames.org did not provide reverse lookup information");
				qDebug() << "no reverse geo lookup; geonames returned\n" << fullReply;
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}
		// next check the oceans API to figure out the body of water
		request.setUrl(geonamesOceanURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));
		reply = rgl->get(request);
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		timer.start(5000);   // 5 secs. timeout
		loop.exec();
		if(timer.isActive()) {
			timer.stop();
			if(reply->error() > 0) {
				report_error("got error accessing oceans API of geonames.org: %s", qPrintable(reply->errorString()));
				goto clear_reply;
			}
			int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			if (v < 200 || v >= 300)
				goto clear_reply;
			QByteArray fullReply = reply->readAll();
			QJsonParseError errorObject;
			QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject);
			if (errorObject.error != QJsonParseError::NoError) {
				report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString()));
				goto clear_reply;
			}
			QJsonObject obj = jsonDoc.object();
			QVariant oceanObject = obj.value("ocean").toVariant();
			QVariantMap oceanName = oceanObject.toMap();
			if (oceanName["name"].isValid()) {
				int idx;
				if (ds->taxonomy.category == NULL)
					ds->taxonomy.category = alloc_taxonomy();
				idx = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN);
				if (idx == -1)
					idx = ds->taxonomy.nr;
				if (idx < TC_NR_CATEGORIES) {
					ds->taxonomy.category[idx].category = TC_OCEAN;
					ds->taxonomy.category[idx].origin = taxonomy::GEOCODED;
					ds->taxonomy.category[idx].value = copy_string(qPrintable(oceanName["name"].toString()));
					if (idx == ds->taxonomy.nr)
						ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}

clear_reply:
		reply->deleteLater();
	}
	rgl->deleteLater();
}
Exemplo n.º 25
0
 void operator()( const cublasStatus_t& result, const char* const file, const unsigned long line ) const
 {
     if ( CUBLAS_STATUS_SUCCESS != result )
         report_error( result, file, line );
 }
Exemplo n.º 26
0
static int
inetport(listener_t *listener)
{
	int fd;
	int opt = 1;

	/*
	 * At first, open a new socket
	 */
	
	fd = comm_socket(listener->addr.ss_family, SOCK_STREAM, 0, "Listener socket");

#ifdef IPV6
	if(listener->addr.ss_family == AF_INET6)
	{
		struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&listener->addr;
		if(!IN6_ARE_ADDR_EQUAL(&in6->sin6_addr, &in6addr_any))
		{
			inetntop(AF_INET6, &in6->sin6_addr, listener->vhost, sizeof(listener->vhost));
			listener->name = listener->vhost;
		}
	} else
#endif
	{
		struct sockaddr_in *in = (struct sockaddr_in *)&listener->addr;
		if(in->sin_addr.s_addr != INADDR_ANY)
		{
			inetntop(AF_INET, &in->sin_addr, listener->vhost, sizeof(listener->vhost));
			listener->name = listener->vhost;
		}	
	}


	if(fd == -1)
	{
		report_error("opening listener socket %s:%s",
			     get_listener_name(listener), 
			     get_listener_name(listener), errno);
		return 0;
	}
	else if((HARD_FDLIMIT - 10) < fd)
	{
		report_error("no more connections left for listener %s:%s",
			     get_listener_name(listener), 
			     get_listener_name(listener), errno);
		comm_close(fd);
		return 0;
	}
	/*
	 * XXX - we don't want to do all this crap for a listener
	 * set_sock_opts(listener);
	 */
	if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &opt, sizeof(opt)))
	{
		report_error("setting SO_REUSEADDR for listener %s:%s",
			     get_listener_name(listener), 
			     get_listener_name(listener), errno);
		comm_close(fd);
		return 0;
	}

	/*
	 * Bind a port to listen for new connections if port is non-null,
	 * else assume it is already open and try get something from it.
	 */

	if(bind(fd, (struct sockaddr *) &listener->addr, GET_SS_LEN(listener->addr)))
	{
		report_error("binding listener socket %s:%s",
			     get_listener_name(listener), 
			     get_listener_name(listener), errno);
		comm_close(fd);
		return 0;
	}

	if(listen(fd, RATBOX_SOMAXCONN))
	{
		report_error("listen failed for %s:%s", 
			     get_listener_name(listener), 
			     get_listener_name(listener), errno);
		comm_close(fd);
		return 0;
	}

	listener->fd = fd;

	/* Listen completion events are READ events .. */

	accept_connection(fd, listener);
	return 1;
}
int main(int argc, char** argv)
{
  char* filepath;

  if(argc < 2)
  {
    print_usage();
  }
  else if(argc > 2)
  {
    print_info = 0;
    print_kmers = 0;
    parse_kmers = 0;

    int i;

    for(i = 1; i < argc-1; i++)
    {
      if(strcasecmp(argv[i], "--print_info") == 0)
      {
        print_info = 1;
      }
      else if(strcasecmp(argv[i], "--print_kmers") == 0)
      {
        print_kmers = 1;
      }
      else if(strcasecmp(argv[i], "--parse_kmers") == 0)
      {
        print_info = 1;
        parse_kmers = 1;
      }
      else
        print_usage();
    }
  }

  filepath = argv[argc-1];

  if(print_info)
    printf("Loading file: %s\n", filepath);

  file_size = get_file_size(filepath);

  FILE* fh = fopen(filepath, "r");

  if(fh == NULL)
  {
    report_error("cannot open file '%s'\n", filepath);
    exit(EXIT_FAILURE);
  }

  if(file_size != -1 && print_info)
  {
    char str[31];
    bytes_to_str(file_size, 0, str);
    printf("File size: %s\n", str);
  }

  buffer = buffer_new(BUFFER_SIZE);

  /*
  // Check sizes
  printf("-- Datatypes --\n");
  printf("int: %i\n", (int)sizeof(int));
  printf("long: %i\n", (int)sizeof(long));
  printf("long long: %i\n", (int)sizeof(long long));
  printf("double: %i\n", (int)sizeof(double));
  printf("long double: %i\n", (int)sizeof(long double));
  */

  if(print_info)
    printf("----\n");

  unsigned int i;

  // Read magic word at the start of header
  char magic_word[7];
  magic_word[6] = '\0';

  my_fread(fh, magic_word, strlen("CORTEX"), "Magic word");

  if(strcmp(magic_word, "CORTEX") != 0)
  {
    fprintf(stderr, "Magic word doesn't match 'CORTEX' (start)\n");
    exit(EXIT_FAILURE);
  }

  // Read version number
  my_fread(fh, &version, sizeof(uint32_t), "binary version");
  my_fread(fh, &kmer_size, sizeof(uint32_t), "kmer size");
  my_fread(fh, &num_of_bitfields, sizeof(uint32_t), "number of bitfields");
  my_fread(fh, &num_of_colours, sizeof(uint32_t), "number of colours");

  if(print_info)
  {
    printf("binary version: %i\n", (int)version);
    printf("kmer size: %i\n", (int)kmer_size);
    printf("bitfields: %i\n", (int)num_of_bitfields);
    printf("colours: %i\n", (int)num_of_colours);
  }

  if(version >= 7)
  {
    my_fread(fh, &expected_num_of_kmers, sizeof(uint64_t), "number of kmers");
    my_fread(fh, &num_of_shades, sizeof(uint32_t), "number of shades");

    if(print_info)
    {
      char tmp[256];
      printf("kmers: %s\n", ulong_to_str(expected_num_of_kmers,tmp));
      printf("shades: %i\n", (int)num_of_shades);
    }
  }

  // Checks

  if(version > 7 || version < 4)
    report_error("Sorry, we only support binary versions 4, 5, 6 & 7\n");

  if(kmer_size % 2 == 0)
    report_error("kmer size is not an odd number\n");

  if(kmer_size < 3)
    report_error("kmer size is less than three\n");

  if(num_of_bitfields * 32 < kmer_size)
    report_error("Not enough bitfields for kmer size\n");

  if((num_of_bitfields-1)*32 >= kmer_size)
    report_error("using more than the minimum number of bitfields\n");

  if(num_of_colours == 0)
    report_error("number of colours is zero\n");

  if(num_of_shades != 0 && (num_of_shades & (num_of_shades-1)))
    report_error("number of shades is not a power of 2\n");

  //

  // Read array of mean read lengths per colour
  uint32_t *mean_read_lens_per_colour = malloc(num_of_colours*sizeof(uint32_t));

  my_fread(fh, mean_read_lens_per_colour, sizeof(uint32_t) * num_of_colours,
           "mean read length for each colour");

  // Read array of total seq loaded per colour
  uint64_t *total_seq_loaded_per_colour = malloc(num_of_colours*sizeof(uint64_t));

  my_fread(fh, total_seq_loaded_per_colour, sizeof(uint64_t) * num_of_colours,
           "total sequance loaded for each colour");

  for(i = 0; i < num_of_colours; i++)
  {
    sum_of_seq_loaded += total_seq_loaded_per_colour[i];
  }

  if(version >= 6)
  {
    sample_names = malloc(sizeof(char*) * num_of_colours);

    for(i = 0; i < num_of_colours; i++)
    {
      uint32_t str_length;
      my_fread(fh, &str_length, sizeof(uint32_t), "sample name length");

      if(str_length == 0)
      {
        sample_names[i] = NULL;
      }
      else
      {
        sample_names[i] = (char*)malloc((str_length+1) * sizeof(char));
        my_fread(fh, sample_names[i], str_length, "sample name");
        sample_names[i][str_length] = '\0';

        // Check sample length is as long as we were told
        size_t sample_name_len = strlen(sample_names[i]);

        if(sample_name_len != str_length)
        {
          // Premature \0 in string
          report_warning("Sample %i name has length %lu but is only %lu chars "
                         "long (premature '\\0')\n",
                         i, str_length, sample_name_len);
        }
      }
    }

    seq_error_rates = malloc(sizeof(long double) * num_of_colours);
    my_fread(fh, seq_error_rates, sizeof(long double) * num_of_colours,
             "seq error rates");

    cleaning_infos = malloc(sizeof(CleaningInfo) * num_of_colours);

    for(i = 0; i < num_of_colours; i++)
    {
      my_fread(fh, &(cleaning_infos[i].tip_cleaning), 1, "tip cleaning");
      my_fread(fh, &(cleaning_infos[i].remove_low_covg_supernodes), 1,
               "remove low covg supernodes");
      my_fread(fh, &(cleaning_infos[i].remove_low_covg_kmers), 1,
               "remove low covg kmers");
      my_fread(fh, &(cleaning_infos[i].cleaned_against_graph), 1,
               "cleaned against graph");

      my_fread(fh, &(cleaning_infos[i].remove_low_covg_supernodes_thresh),
               sizeof(int32_t), "remove low covg supernode threshold");
    
      my_fread(fh, &(cleaning_infos[i].remove_low_covg_kmers_thresh),
               sizeof(int32_t), "remove low covg kmer threshold");

      if(version > 6)
      {
        if(cleaning_infos[i].remove_low_covg_supernodes_thresh < 0)
        {
          report_warning("Binary header gives sample %i a cleaning threshold of "
                         "%i for supernodes (should be >= 0)\n",
                         i, cleaning_infos[i].remove_low_covg_supernodes_thresh);
        }
        if(cleaning_infos[i].remove_low_covg_kmers_thresh < 0)
        {
          report_warning("Binary header gives sample %i a cleaning threshold of "
                         "%i for kmers (should be >= 0)\n",
                         i, cleaning_infos[i].remove_low_covg_kmers_thresh);
        }
      }

      if(!cleaning_infos[i].remove_low_covg_supernodes &&
         cleaning_infos[i].remove_low_covg_supernodes_thresh > 0)
      {
        report_warning("Binary header gives sample %i a cleaning threshold of "
                       "%i for supernodes when no cleaning was performed\n",
                       i, cleaning_infos[i].remove_low_covg_supernodes_thresh);
      }

      if(!cleaning_infos[i].remove_low_covg_kmers &&
         cleaning_infos[i].remove_low_covg_kmers_thresh > 0)
      {
        report_warning("Binary header gives sample %i a cleaning threshold of "
                       "%i for kmers when no cleaning was performed\n",
                       i, cleaning_infos[i].remove_low_covg_kmers_thresh);
      }

      uint32_t name_length;
      my_fread(fh, &name_length, sizeof(uint32_t), "graph name length");

      if(name_length == 0)
      {
        cleaning_infos[i].name_of_graph_clean_against = NULL;
      }
      else
      {
        cleaning_infos[i].name_of_graph_clean_against
          = (char*)malloc((name_length + 1) * sizeof(char));

        my_fread(fh, cleaning_infos[i].name_of_graph_clean_against,
                 name_length, "graph name length");

        cleaning_infos[i].name_of_graph_clean_against[name_length] = '\0';
      
        // Check sample length is as long as we were told
        size_t cleaned_name_len
          = strlen(cleaning_infos[i].name_of_graph_clean_against);

        if(cleaned_name_len != name_length)
        {
          // Premature \0 in string
          report_warning("Sample [%i] cleaned-against-name has length %u but is "
                         "only %u chars long (premature '\\0')\n",
                         i, name_length, cleaned_name_len);
        }
      }
    }
  }

  // Print colour info

  if(print_info)
  {
    for(i = 0; i < num_of_colours; i++)
    {
      printf("-- Colour %i --\n", i);

      if(version >= 6)
      {
        // Version 6 only output
        printf("  sample name: '%s'\n", sample_names[i]);
      }

      char tmp[32];

      printf("  mean read length: %u\n",
             (unsigned int)mean_read_lens_per_colour[i]);
      printf("  total sequence loaded: %s\n",
             ulong_to_str(total_seq_loaded_per_colour[i], tmp));
      
      if(version >= 6)
      {
        // Version 6 only output
        printf("  sequence error rate: %Lf\n", seq_error_rates[i]);

        printf("  tip clipping: %s\n",
               (cleaning_infos[i].tip_cleaning == 0 ? "no" : "yes"));

        printf("  remove low coverage supernodes: %s [threshold: %i]\n",
               cleaning_infos[i].remove_low_covg_supernodes ? "yes" : "no",
               cleaning_infos[i].remove_low_covg_supernodes_thresh);

        printf("  remove low coverage kmers: %s [threshold: %i]\n",
               cleaning_infos[i].remove_low_covg_kmers ? "yes" : "no",
               cleaning_infos[i].remove_low_covg_kmers_thresh);

        printf("  cleaned against graph: %s [against: '%s']\n",
               cleaning_infos[i].cleaned_against_graph ? "yes" : "no",
               (cleaning_infos[i].name_of_graph_clean_against == NULL
                  ? "" : cleaning_infos[i].name_of_graph_clean_against));
      }
    }

    printf("--\n");
  }

  // Read magic word at the end of header
  my_fread(fh, magic_word, strlen("CORTEX"), "magic word (end)");

  if(strcmp(magic_word, "CORTEX") != 0)
  {
    report_error("magic word doesn't match 'CORTEX' (end): '%s'\n", magic_word);
    exit(EXIT_FAILURE);
  }

  // Calculate number of kmers
  if(version < 7 && file_size != -1)
  {
    size_t bytes_remaining = file_size - num_bytes_read;
    size_t num_bytes_per_kmer = sizeof(uint64_t) * num_of_bitfields +
                                sizeof(uint32_t) * num_of_colours +
                                sizeof(uint8_t) * num_of_colours;

    expected_num_of_kmers = bytes_remaining / num_bytes_per_kmer;

    size_t excess = bytes_remaining - (expected_num_of_kmers * num_bytes_per_kmer);

    if(excess > 0)
    {
      report_error("Excess bytes. Bytes:\n  file size: %lu;\n  for kmers: %lu;"
                   "\n  num kmers: %lu;\n  per kmer: %lu;\n  excess: %lu\n",
                   file_size, bytes_remaining, expected_num_of_kmers,
                   num_bytes_per_kmer, excess);
    }
  }

  if(print_info)
  {
    char num_str[50];
    printf("Expected number of kmers: %s\n",
           ulong_to_str(expected_num_of_kmers, num_str));
    printf("----\n");
  }

  // Finished parsing header
  if(!parse_kmers && !print_kmers)
  {
    print_kmer_stats();
    fclose(fh);
    exit(EXIT_SUCCESS);
  }


  shade_bytes = num_of_shades >> 3;
  size_t shade_array_bytes = shade_bytes * num_of_colours;

  // Kmer data
  uint64_t* kmer = malloc(sizeof(uint64_t) * num_of_bitfields);
  uint32_t* covgs = malloc(sizeof(uint32_t) * num_of_colours);
  uint8_t* edges = malloc(sizeof(uint8_t) * num_of_colours);
  uint8_t* shade_data = malloc(shade_array_bytes);
  uint8_t* shend_data = malloc(shade_array_bytes);

  if(kmer == NULL || covgs == NULL || edges == NULL ||
     shade_data == NULL || shend_data == NULL) {
    report_error("Out of memory");
    exit(EXIT_SUCCESS);
  }

  // Convert values to strings
  char* seq = malloc(sizeof(char) * kmer_size);
  char kmer_colour_edge_str[9];

  // Check top word of each kmer
  int bits_in_top_word = 2 * (kmer_size % 32);
  uint64_t top_word_mask = (~(uint64_t)0) << bits_in_top_word;

  size_t num_bytes_per_bkmer = sizeof(uint64_t)*num_of_bitfields;

  // Read kmer in bytes so we can see if there are extra bytes at the end of
  // the file
  size_t bytes_read;

  // while((bytes_read = fread(kmer, 1, num_bytes_per_bkmer, fh)) > 0)
  while((bytes_read = fread_buf(fh, kmer, num_bytes_per_bkmer, buffer)) > 0)
  {
    if(bytes_read != num_bytes_per_bkmer)
    {
      report_error("unusual extra bytes [%i] at the end of the file\n",
                   (int)bytes_read);
      break;
    }
    num_bytes_read += bytes_read;

    my_fread(fh, covgs, sizeof(uint32_t) * num_of_colours, "kmer covg");
    my_fread(fh, edges, sizeof(uint8_t) * num_of_colours, "kmer edges");

    if(version >= 7)
    {
      uint8_t *shades = shade_data, *shends = shend_data;
      for(i = 0; i < num_of_colours; i++)
      {
        my_fread(fh, shades, sizeof(uint8_t) * shade_bytes, "shades");
        my_fread(fh, shends, sizeof(uint8_t) * shade_bytes, "shade ends");
        shades += shade_bytes;
        shends += shade_bytes;
      }
    }

    //
    // Kmer checks
    //

    // Check top bits of kmer
    if(kmer[0] & top_word_mask)
    {
      if(num_of_oversized_kmers == 0)
      {
        report_error("oversized kmer [index: %lu]\n", num_of_kmers_read);

        for(i = 0; i < num_of_bitfields; i++)
        {
          fprintf(stderr, "  word %i: ", i);
          print_binary(stderr, kmer[i]);
          fprintf(stderr, "\n");
        }
      }

      num_of_oversized_kmers++;
    }

    // Check for all-zeros (i.e. all As kmer: AAAAAA)
    uint64_t kmer_words_or = 0;

    for(i = 0; i < num_of_bitfields; i++)
      kmer_words_or |= kmer[i];

    if(kmer_words_or == 0)
    {
      if(num_of_all_zero_kmers == 1)
      {
        report_error("more than one all 'A's kmers seen [index: %lu]\n",
                     num_of_kmers_read);
      }

      num_of_all_zero_kmers++;
    }

    // Check covg is 0 for all colours
    for(i = 0; i < num_of_colours && covgs[i] == 0; i++);

    if(i == num_of_colours)
    {
      if(num_of_zero_covg_kmers == 0)
      {
        report_warning("a kmer has zero coverage in all colours [index: %lu]\n",
                       num_of_kmers_read);
      }

      num_of_zero_covg_kmers++;
    }

    // Print?
    if(print_kmers)
    {
      binary_kmer_to_seq(kmer, seq, kmer_size, num_of_bitfields);
      printf("%s", seq);

      // Print coverages
      for(i = 0; i < num_of_colours; i++)
        printf(" %li", (unsigned long)covgs[i]);

      // Print edges
      for(i = 0; i < num_of_colours; i++)
        printf(" %s", get_edges_str(edges[i], kmer_colour_edge_str));

      if(version >= 7 && num_of_shades > 0)
      {
        for(i = 0; i < num_of_colours; i++)
        {
          putc(' ', stdout);
          print_colour_shades(shade_data + i*shade_bytes, shend_data + i*shade_bytes);
        }
      }

      putc('\n', stdout);
    }

    num_of_kmers_read++;

    for(i = 0; i < num_of_colours; i++)
      sum_of_covgs_read += covgs[i];
  }

  if(num_of_kmers_read != expected_num_of_kmers)
  {
    report_error("Expected %lu kmers, read %lu\n",
                 expected_num_of_kmers, num_of_kmers_read);
  }

  if(print_kmers && print_info)
    printf("----\n");

  // check for various reading errors
  if(errno != 0)
  {
    report_error("errno set [%i]\n", (int)errno);
  }

  int err;
  if((err = ferror(fh)) != 0)
  {
    report_error("occurred after file reading [%i]\n", err);
  }

  // For testing output
  //num_of_bitfields = 2;
  //num_of_kmers_read = 3600000000;
  //num_of_kmers_read = 12345;
  //num_of_kmers_read = 3581787;
  //num_of_kmers_read = 0;

  print_kmer_stats();

  fclose(fh);

  free(kmer);
  free(covgs);
  free(edges);
  free(shade_data);
  free(shend_data);

  buffer_free(buffer);

  if((print_kmers || parse_kmers) && print_info)
  {
    printf("----\n");
    if(num_warnings > 0 || num_errors > 0)
      printf("Warnings: %u; Errors: %u\n", num_warnings, num_errors);
    if(num_errors == 0)
      printf(num_warnings ? "Binary may be ok\n" : "Binary is valid\n");
  }

  exit(EXIT_SUCCESS);
}
Exemplo n.º 28
0
int mysql_dumper_dump(struct mysql_login_info *mysql_login_info, const char *outputdir, const char *dbname, const char *tablename, const char *query, size_t query_len, struct mysql_dumper_type *types) {
    MYSQL mysql;
    MYSQL_STMT *stmt = NULL;
    mysql_init(&mysql);
    my_bool b_flag = 1;
    if (0 != mysql_options(&mysql, MYSQL_OPT_RECONNECT, (const char *)&b_flag))
        return report_error(&mysql);

    if (NULL == mysql_real_connect(&mysql, mysql_login_info->host, mysql_login_info->user, mysql_login_info->pass, mysql_login_info->db, mysql_login_info->port, NULL, CLIENT_COMPRESS))
        return report_error(&mysql);

    b_flag = 0;
    if (0 != mysql_options(&mysql, MYSQL_REPORT_DATA_TRUNCATION, (const char *)&b_flag))
        return report_error(&mysql);

    stmt = mysql_stmt_init(&mysql);
    if (!stmt)
        return report_error(&mysql);

    if (0 != mysql_stmt_prepare(stmt, query, query_len))
        return report_stmt_error(&mysql, stmt);

    MYSQL_RES *rs = mysql_stmt_result_metadata(stmt);
    if (!rs)
        return report_stmt_error(&mysql, stmt);

    unsigned int n = mysql_num_fields(rs);
    MYSQL_FIELD *fields = mysql_fetch_fields(rs);
    int field_types[n];
    MYSQL_BIND bind[n];
    my_bool is_null[n];
    unsigned long length[n];
    my_bool error[n];
    memset(bind, 0, sizeof(MYSQL_BIND) * n);
    int null_terminate_str[n];
    memset(null_terminate_str, 0, sizeof(int) * n);

    struct file_writer ffields[n];
    struct file_writer vfields[2][n];

    struct vmbuf buf = VMBUF_INITIALIZER;
    vmbuf_init(&buf, 4096);
    vmbuf_sprintf(&buf, "%s/%s/%s/schema.txt", outputdir, dbname, tablename);
    mkdir_for_file_recursive(vmbuf_data(&buf));
    int fdschema = creat(vmbuf_data(&buf), 0644);
    struct vmfile ds_txt = VMFILE_INITIALIZER;
    vmbuf_reset(&buf);
    vmbuf_sprintf(&buf, "%s/%s/%s/ds.txt", outputdir, dbname, tablename);
    if (0 > vmfile_init(&ds_txt, vmbuf_data(&buf), 4096))
        return LOGGER_ERROR("failed to create: %s", vmbuf_data(&buf)), vmbuf_free(&buf), -1;
    vmfile_sprintf(&ds_txt, "DS_LOADER_BEGIN()\n");
    vmfile_sprintf(&ds_txt, "/*\n * DB: %s\n */\n", dbname);
    vmfile_sprintf(&ds_txt, "#undef DB_NAME\n#define DB_NAME %s\n", dbname);
    ssize_t len = 80 - strlen(tablename);
    if (len < 0) len = 4;
    char header[len];
    memset(header, '=', len);
    vmfile_sprintf(&ds_txt, "/* %.*s[ %s ]%.*s */\n", (int)len / 2, header, tablename, (int)(len - (len / 2)), header);
    vmfile_sprintf(&ds_txt, "#   undef TABLE_NAME\n#   define TABLE_NAME %s\n", tablename);
    /*
     * initialize output files
     */
    unsigned int i;
    for (i = 0; i < n; ++i) {
        file_writer_make(&ffields[i]);
        file_writer_make(&vfields[0][i]);
        file_writer_make(&vfields[1][i]);
    }

    struct hashtable ht_types = HASHTABLE_INITIALIZER;
    hashtable_init(&ht_types, 32);
    if (NULL != types) {
        struct mysql_dumper_type *t = types;
        for (; t->name; ++t) {
            /* storing ptr here which points to static str */
            hashtable_insert(&ht_types, t->name, strlen(t->name), t, sizeof(struct mysql_dumper_type));
        }
    }
    /*
     * parse meta data and construct bind array
     */
    int err = 0;
    for (i = 0; i < n; ++i) {
        field_types[i] = fields[i].type;
        bind[i].is_unsigned = IS_UNSIGNED(fields[i].flags);

        int64_t ds_type = -1;
        const char *ds_type_str = "VAR";
        /*
         * handle overrides
         */
        while (NULL != types) {
            uint32_t ofs = hashtable_lookup(&ht_types, fields[i].name, strlen(fields[i].name));
            if (!ofs) break;
            struct mysql_dumper_type *type = (struct mysql_dumper_type *)hashtable_get_val(&ht_types, ofs);
            null_terminate_str[i] = MYSQL_DUMPER_CSTR & type->flags;
            if (type->mysql_type)
                field_types[i] = type->mysql_type;
            bind[i].is_unsigned = (type->flags & MYSQL_DUMPER_UNSIGNED) > 0 ? 1 : 0;
            break;
        }
        vmbuf_reset(&buf);
        vmbuf_sprintf(&buf, "%s/%s/%s/%s", outputdir, dbname, tablename, fields[i].name);

        mkdir_for_file_recursive(vmbuf_data(&buf));
        if (is_var_length_field(field_types[i])) {
            size_t ofs = vmbuf_wlocpos(&buf);
            vmbuf_sprintf(&buf, ".ofs");
            if (0 > (err = file_writer_init(&vfields[0][i], vmbuf_data(&buf))))
                break;
            vmbuf_wlocset(&buf, ofs);
            vmbuf_sprintf(&buf, ".dat");
            if (0 > (err = file_writer_init(&vfields[1][i], vmbuf_data(&buf))))
                break;
        } else {
            ds_type = get_ds_type(field_types[i], bind[i].is_unsigned);
            const char *s = get_ds_type_str(ds_type);
            if (*s) ds_type_str = s;
            if (0 > (err = file_writer_init(&ffields[i], vmbuf_data(&buf))) ||
                0 > (err = file_writer_write(&ffields[i], &ds_type, sizeof(ds_type))))
                break;;
        }
        len = ribs_mysql_get_storage_size(field_types[i], fields[i].length);
        if (fdschema > 0)
            dprintf(fdschema, "%03d  name = %s, size=%zu, length=%lu, type=%s (%s), is_prikey=%d, ds_type=%s\n", i, fields[i].name, len, fields[i].length, ribs_mysql_get_type_name(field_types[i]), bind[i].is_unsigned ? "unsigned" : "signed", IS_PRI_KEY(fields[i].flags), ds_type_str);
        if (is_var_length_field(field_types[i])) {
            vmfile_sprintf(&ds_txt, "        DS_VAR_FIELD_LOADER(%s)\n", fields[i].name);
        } else {
            vmfile_sprintf(&ds_txt, "        DS_FIELD_LOADER(%s, %s)\n", ds_type_str, fields[i].name);
        }
        bind[i].buffer_type = field_types[i];
        bind[i].buffer_length = len;
        bind[i].buffer = malloc(len);
        bind[i].is_null = &is_null[i];
        bind[i].length = &length[i];
        bind[i].error = &error[i];
    }
    hashtable_free(&ht_types);
    mysql_free_result(rs);
    close(fdschema);
    //vmfile_sprintf(&ds_txt, "/*\n * TABLE END: %s\n */\n", tablename);
    vmfile_sprintf(&ds_txt, "DS_LOADER_END()\n");
    vmfile_close(&ds_txt);
    /*
     * execute & bind
     */
    if (0 != err ||
        0 != mysql_stmt_execute(stmt) ||
        0 != mysql_stmt_bind_result(stmt, bind)) {
        err = -1;
        report_stmt_error(&mysql, stmt);
        goto dumper_close_writer;
    }
    char zeros[4096];
    memset(zeros, 0, sizeof(zeros));
    int mysql_err = 0;
    size_t count = 0, num_rows_errors = 0;
    /*
     * write all rows to output files
     */
    while (0 == (mysql_err = mysql_stmt_fetch(stmt))) {
        int b = 0;
        for (i = 0; i < n && !b; ++i)
            b = b || error[i];
        if (b) {
            ++num_rows_errors;
            continue;
        }
        for (i = 0; i < n; ++i) {
            if (is_var_length_field(field_types[i])) {
                size_t ofs = file_writer_wlocpos(&vfields[1][i]);
                if (0 > (err = file_writer_write(&vfields[0][i], &ofs, sizeof(ofs))) ||
                    0 > (err = file_writer_write(&vfields[1][i], is_null[i] ? NULL : bind[i].buffer, is_null[i] ? 0 : length[i])))
                    goto dumper_error;
                if (null_terminate_str[i]) {
                    const char c = '\0';
                    if (0 > (err = file_writer_write(&vfields[1][i], &c, sizeof(c))))
                        goto dumper_error;
                }
            } else {
                if (0 > (err = file_writer_write(&ffields[i], is_null[i] ? zeros : bind[i].buffer, bind[i].buffer_length)))
                    goto dumper_error;
            }
        }
        ++count;
    }
    /* no dumper errors */
    goto dumper_ok;
 dumper_error:
    LOGGER_ERROR("failed to write data, aborting");
 dumper_ok:
    /* we are done with mysql, close it */
    mysql_stmt_close(stmt);
    mysql_close(&mysql);
    LOGGER_INFO("%s: %zu records, %zu skipped", tablename, count, num_rows_errors);
    /* check for mysql errors */
    if (mysql_err != MYSQL_NO_DATA) {
        LOGGER_ERROR("mysql_stmt_fetch returned an error (code=%d)\n", mysql_err);
        err = -1;
    }
 dumper_close_writer:
    /*
     * finalize & free memory
     */
    for (i = 0; i < n; ++i) {
        if (is_var_length_field(field_types[i])) {
            size_t ofs = file_writer_wlocpos(&vfields[1][i]);
            if (0 > (err = file_writer_write(&vfields[0][i], &ofs, sizeof(ofs))))
                LOGGER_ERROR("failed to write offset");
            file_writer_close(&vfields[0][i]);
            file_writer_close(&vfields[1][i]);
        } else {
            file_writer_close(&ffields[i]);
        }
        free(bind[i].buffer);
    }
    vmbuf_free(&buf);
    return err;
}
Exemplo n.º 29
0
int main(int argc, char **argv)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    unsigned short rc;

    char *new_at_file;
    char *old_at_file;
    char *line;
    int i;
    DWORD exitCode;

    if (argc<3 || argv[1][0] != '-' || (argv[1][1] != 'c' && argv[1][1] != 'm')) {
        fprintf(stderr, "Usage: fixpath -c|m<path@path@...> /cygdrive/c/WINDOWS/notepad.exe /cygdrive/c/x/test.txt\n");
        exit(0);
    }

    if (getenv("DEBUG_FIXPATH") != NULL) {
      fprintf(stderr, "fixpath input line >%s<\n", strstr(GetCommandLine(), argv[1]));
    }

    if (argv[1][1] == 'c' && argv[1][2] == '\0') {
      if (getenv("DEBUG_FIXPATH") != NULL) {
        fprintf(stderr, "using cygwin mode\n");
      }
      replace_cygdrive = replace_cygdrive_cygwin;
    } else if (argv[1][1] == 'm') {
      if (getenv("DEBUG_FIXPATH") != NULL) {
        fprintf(stderr, "using msys mode, with path list: %s\n", &argv[1][2]);
      }
      setup_msys_path_list(argv[1]);
      replace_cygdrive = replace_cygdrive_msys;
    } else {
      fprintf(stderr, "Unknown mode: %s\n", argv[1]);
      exit(-1);
    }
    line = replace_cygdrive(strstr(GetCommandLine(), argv[2]));

    for (i=1; i<argc; ++i) {
       if (argv[i][0] == '@') {
          // Found at-file! Fix it!
          old_at_file = replace_cygdrive(argv[i]);
          new_at_file = fix_at_file(old_at_file);
          line = replace_substring(line, old_at_file, new_at_file);
       }
    }

    if (getenv("DEBUG_FIXPATH") != NULL) {
      fprintf(stderr, "fixpath converted line >%s<\n", line);
    }

    ZeroMemory(&si,sizeof(si));
    si.cb=sizeof(si);
    ZeroMemory(&pi,sizeof(pi));

    rc = CreateProcess(NULL,
                       line,
                       0,
                       0,
                       TRUE,
                       0,
                       0,
                       0,
                       &si,
                       &pi);
    if(!rc) {
      // Could not start process for some reason.  Try to report why:
      report_error();
      exit(rc);
    }

    WaitForSingleObject(pi.hProcess,INFINITE);
    GetExitCodeProcess(pi.hProcess,&exitCode);

    if (getenv("DEBUG_FIXPATH") != NULL) {
      for (i=0; i<num_files_to_delete; ++i) {
        fprintf(stderr, "Not deleting temporary fixpath file %s\n",
                files_to_delete[i]);
      }
    }
    else {
      for (i=0; i<num_files_to_delete; ++i) {
        remove(files_to_delete[i]);
      }
    }

    exit(exitCode);
}
Exemplo n.º 30
0
int
engine_read_message (time_t delay)
{
  fd_set read_set, write_set;
  struct timeval wt;
  int nfds, length, i;
  unsigned int fdflags;
  int fdtype;
  void *fdvalue;
  aClient *client_p;

  engine_get_fdsets (&read_set, &write_set);

  wt.tv_sec = delay;
  wt.tv_usec = 0;

  nfds = select (MAXCONNECTIONS, &read_set, &write_set, NULL, &wt);
  if (nfds == -1)
  {
    if (((errno == EINTR) || (errno == EAGAIN)))
      return -1;
    report_error ("select %s:%s", &me);
    sleep (5);
    return -1;
  }
  else if (nfds == 0)
    return 0;

  if (delay)
    NOW = timeofday = time (NULL);

  for (i = 0; i < MAXCONNECTIONS; i++)
  {
    get_fd_info (i, &fdtype, &fdflags, &fdvalue);

    client_p = NULL;
    length = -1;

    if (nfds)
    {
      int rr = FD_ISSET (i, &read_set);
      int rw = FD_ISSET (i, &write_set);

      if (rr || rw)
        nfds--;
      else
        continue;

      fdfprintf (stderr, "fd %d: %s%s\n", i, rr ? "read " : "",
                 rw ? "write" : "");

      switch (fdtype)
      {
         case FDT_NONE:
           break;

         case FDT_AUTH:
           client_p = (aClient *) fdvalue;
           if (rr)
             read_authports (client_p);
           if (rw && client_p->authfd >= 0)
             send_authports (client_p);
           check_client_fd (client_p);
           break;

         case FDT_LISTENER:
           client_p = (aClient *) fdvalue;
           if (rr)
             accept_connection (client_p);
           break;

         case FDT_RESOLVER:
#ifdef USE_ADNS
           dns_do_callbacks ();
#else
           do_dns_async ();
#endif
           break;

         case FDT_CLIENT:
           client_p = (aClient *) fdvalue;
           readwrite_client (client_p, rr, rw);
           break;

         default:
           abort ();            /* unknown client type? bail! */
      }
    }
    else
      break;                    /* no more fds? break out of the loop */
  }                             /* end of for() loop for testing selected sockets */

  return 0;
}