Example #1
0
/* PUBLIC */
Fpa_chunk flist_delete(Fpa_chunk f, Term x)
{
    if (f == NULL)
        fprintf(stderr, "WARNING: flist_delete, item %p not found (1)!\n", x);
    else if (FLT(x,FLAST(f)))
        f->next = flist_delete(f->next, x);
    else {
        int n = f->n;
        int i = FMAX - n;
        while (i < FMAX && FLT(x,f->d[i]))
            i++;
        if (x != f->d[i])
            fprintf(stderr, "WARNING: flist_delete, item %p not found (2)!\n", x);
        else {
            /* delete and close the hole */
            int j;
            for (j = i; j > FMAX-n; j--)
                f->d[j] = f->d[j-1];
            f->d[j] = NULL;
            f->n = n-1;
            if (f->n == 0) {
                /* delete this chunk */
                Fpa_chunk next = f->next;
                free_fpa_chunk(f);
                f = next;
            }
            else {
                /* try to join this chunk with the next */
                f = consolidate(f);
            }
        }
    }
    return f;
}  /* flist_delete */
Example #2
0
/*
First, we remove the minimum key from the root list and splice its 
children into the root list. Except for updating the parent pointers, 
this takes O(1) time. Then we scan through the root list to find the 
new smallest key and update the parent pointers of the new roots. 
This scan could take O(n) time in the worst case. To bring down the 
amortized deletion time (see further on), we apply a Cleanup 
algorithm, which links trees of equal degree until there is only one 
root node of any particular degree.
*/
static PQueueElement * ExtractMin(PQueue *h)
{
    PQueueElement *ret;
    PQueueElement *x, *y, *orig;

    ret = h->Minimum;

    orig = NULL;
    /* put all the children on the root list */
    /* for true consistancy, we should use remove */
    for(x = ret->Child; x != orig && x != NULL;) {
        if (orig == NULL)
            orig = x;
        y = x->Right;
        x->Parent = NULL;
        insertrootlist(h, x);
        x = y;
    }
    /* remove minimum from root list */
    removerootlist(h, ret);
    h->count--;

    /* if we aren't empty, consolidate the heap */
    if (h->count == 0)
        h->Minimum = NULL;
    else {
        h->Minimum = ret->Right;
        consolidate(h);
    }

    h->timestamp++;

    return ret;
}
Example #3
0
 typename FibHeap<Key, Data, Compare>::Node* FibHeap<Key, Data, Compare>::extract_minimum(){
     if (root==nullptr)
         throw logic_error("Heap is empty. Don't try to extract minimum.");
     Node* answer = root;
     if (root!=nullptr){
         Node* current_child = root->child;
         for (int i=1; i<=root->degree; i++){
             current_child->parent = nullptr;
             Node* temp = current_child;
             current_child = current_child->right;
             insert_to_root_list(root, temp);
         }
         if (root == root->right){
             root = nullptr;
             number_of_nodes = 0;
         }else{
             root = root->right;
             erase_from_root_list(answer);
             answer->child = nullptr;
             consolidate();
             number_of_nodes--;
         }
     }
     return answer;
 }
Example #4
0
SparseMat::SparseMat(const SparseMat &source,
			     const DoFMap &rowmap,
			     const DoFMap &colmap)
  : nnz_(0),
    nrows_(rowmap.range()),
    ncols_(colmap.range()),
    consolidated_(true)	       // true, because mtx is initially empty
{
  data.resize(nrows_);
  nonempty_col.resize(ncols_, false);
  
  for(SparseMatConstIterator ij=source.begin(); ij<source.end(); ++ij) {
    assert(ij.row() < rowmap.domain()); // row is unsigned, dont check >= 0
    int i = rowmap[ij.row()];

    assert(data.size()!=0 || i==-1);
    assert(i < (int) rowmap.range());

    if(i >= 0) {
      assert(ij.col() < colmap.domain());
      int j = colmap[ij.col()];
      assert(j < (int) colmap.range() && j >= -1);
      if(j >= 0) {
	insert(i, j, *ij);	// unsets consolidated_.
      }
    }
  }
  consolidate();
}
Example #5
0
T fibheap<T>::deleteExtreme() {
    T retVal = extreme->getValue();
    trees.merge(*extreme->getChildren());
    trees.remove(extreme);
    heights[extreme->calculateHeight()]->remove(extreme);
    for(auto i:*extreme->getChildren()) {
        heights[i->getHeight()]->push_back(i);
        i->removeParent();
    }
    delete extreme;
    consolidate();
    //Find new extreme
    extreme = trees.front();
    if(maxHeap) {
        for(auto i:trees) {
            if(i->getKey() > extreme->getKey()) {
                extreme = i;
            }
        }
    } else {
        for(auto i:trees) {
            if(i->getKey() < extreme->getKey()) {
                extreme = i;
            }
        }
    }
    return retVal;
}
Example #6
0
void do_sell( char_data* ch, char* argument )
{
  char_data*   keeper;
  thing_array*  array;
  obj_data*       obj;

  if( ( keeper = find_keeper( ch ) ) == NULL )
    return;

  if( is_set( &ch->in_room->room_flags, RFLAG_PET_SHOP ) ) {
    process_tell( keeper, ch, "We don't buy pets." );
    ch->reply = keeper;
    return;
    }

  if( *argument == '\0' ) {
    send( ch, "Sell what?\r\n" );
    return;
    }

  if( ( array = several_things( ch, argument, "sell", 
    &ch->contents ) ) == NULL ) 
    return;

  thing_array   subset  [ 5 ];
  thing_func*     func  [ 5 ]  = { cursed, stolen, uninterested,
                                   not_empty, sold };

  sort_objects( ch, *array, keeper, 5, subset, func );

  page_priv( ch, NULL, empty_string );
  page_priv( ch, &subset[1], "don't own" );
  page_priv( ch, &subset[2], "isn't interested in", keeper );
  page_priv( ch, &subset[0], "can't let go of" );
  page_priv( ch, &subset[3], NULL, NULL, "isn't empty", "aren't empty" );
  page_publ( ch, &subset[4], "sell", keeper, "to", "for" );

  for( int i = 0; i < subset[4]; i++ ) {
    obj = (obj_data*) subset[4][i];
    obj = (obj_data*) obj->From( obj->selected );

    set_bit( obj->extra_flags, OFLAG_IDENTIFIED );
    set_bit( obj->extra_flags, OFLAG_KNOWN_LIQUID );

    if( obj->pIndexData->item_type == ITEM_WAND
      || obj->pIndexData->item_type == ITEM_STAFF ) 
      obj->value[3] = obj->pIndexData->value[3];

    free_string( obj->label, MEM_OBJECT );
    obj->label = empty_string;

    obj->owner = NULL;
    add_coins( ch, obj->temp );
    obj->To( keeper );
    consolidate( obj );
    }

  delete array;
}
Example #7
0
MojErr MojBuffer::release(MojAutoPtr<Chunk>& chunkOut)
{
	MojErr err = consolidate();
	MojErrCheck(err);
	MojAssert(m_chunks.size() <= 1);
	if (m_chunks.empty()) {
		chunkOut.reset();
	} else {
		chunkOut.reset(m_chunks.popFront());
	}
	return MojErrNone;
}
Example #8
0
	/** Deletes and returns item with minimal key
	 * Have amortized time of O(log n)
	 * @return item with minimal key
	 */
	int extract_min(ScalarType& ret_key)
	{
		fibonacci_heap_node *min_node;
		fibonacci_heap_node *child, *next_child;

		int result;

		if(num_nodes == 0)
			return -1;

		min_node = min_root;
		if(min_node == NULL)
			return -1; // heap is empty now

		child = min_node->child;
		while(child != NULL && child->parent != NULL)
		{
			next_child = child->right;

			// delete current child from childs list
			child->left->right = child->right;
			child->right->left = child->left;

			add_to_roots(child);

			// next iteration
			child = next_child;
		}

		// delete minimun from root list
		min_node->left->right = min_node->right;
		min_node->right->left = min_node->left;

		num_trees--;

		if(min_node == min_node->right)
		{
			min_root = NULL; // remove last element
		}
		else
		{
			min_root = min_node->right;
			consolidate();
		}

		result = min_node->index;
		ret_key = min_node->key;
		clear_node(result);

		num_nodes--;

		return result;
	}
Example #9
0
MojErr MojBuffer::data(const MojByte*& dataOut, MojSize& sizeOut)
{
	dataOut = NULL;
	sizeOut = 0;
	MojErr err = consolidate();
	MojErrCheck(err);
	if (m_chunks.size() == 1) {
		// if we only have one chunk, just return it's data
		const Chunk* chunk = m_chunks.front();
		dataOut = chunk->data();
		sizeOut = chunk->dataSize();
	}
	return MojErrNone;
}
Example #10
0
TETRIS_API TetrisResult tetris_move_piece(Tetris *object, Z2DInt8 movement)
	{
	TetrisPiece const *piece = object->piece;
	Z2DInt point = {object->piece_point.x + movement.x, object->piece_point.y + movement.y};
	zuint8 hit = bounds_hit(object, piece, point);

	if (hit)
		{
		if (hit == HIT_SIDE) return TETRIS_RESULT_HIT;
		consolidate(object);
		return TETRIS_RESULT_CONSOLIDATED;
		}

	if (content_hit(object, piece, point))
		{
		if (movement.y <= 0) return TETRIS_RESULT_HIT;
		if (object->piece_point.y + piece->a.y < 0) return TETRIS_RESULT_GAME_OVER;
		consolidate(object);
		return TETRIS_RESULT_CONSOLIDATED;
		}

	object->piece_point = point;
	return Z_OK;
	}
Example #11
0
// Add a scalar multiple of another matrix.
SparseMat &SparseMat::add(double alpha, const SparseMat &other) {
  assert(other.nrows() == nrows_ && other.ncols() == ncols_);
  if(alpha != 1.0) {
    for(const_iterator iter = other.begin(); iter<other.end(); ++iter)
      insert(iter.row(), iter.col(), alpha*iter.value());
  }
  else {			// alpha == 1.0
    for(const_iterator iter = other.begin(); iter<other.end(); ++iter)
      insert(iter.row(), iter.col(), iter.value());
  }
  // TODO OPT: Don't consolidate here -- there might be more additions
  // later.  Consolidate explicitly only.
  consolidate();
  return *this;
}
Example #12
0
TETRIS_API TetrisResult tetris_drop_piece(Tetris *object)
	{
	TetrisPiece const *piece = object->piece;
	Z2DInt point = object->piece_point;

	for (	point.y++;
		!bounds_hit(object, piece, point) && !content_hit(object, piece, point);
		point.y++
	);

	if ((object->piece_point.y = point.y - 1) + piece->a.y < 0)
		return TETRIS_RESULT_GAME_OVER;

	consolidate(object);
	return TETRIS_RESULT_CONSOLIDATED;
	}
Example #13
0
void add_coins( char_data* ch, int amount, char* message )
{
  obj_data*  obj;
  int        num  [ 4 ];
  int          i;

  for( i = MAX_COIN - 1; i >= 0; i-- ) {
    if( ( num[i] = amount/coin_value[i] ) > 0 ) {
      amount -= num[i]*coin_value[i];
      obj = create( get_obj_index( coin_vnum[i] ), num[i] ); 
      obj->To( ch );
      consolidate( obj );
      }
    }

  if( message != NULL ) 
    send( ch, "%s%s.\r\n", message, coin_phrase( num ) );
}
Example #14
0
// 提取最小结点
int extractMin(FibonaciHeap *heap)
{
	if (heap->min == NULL)	return EMPTY_HEAP;

	int mini = heap->min->value;
	// 将最小结点的孩子结点插入到根链表中
	FibonaciNode *child = heap->min->child;
	if (child != NULL)
	{
		child->left->right = NULL;
		while (child != NULL)
		{
			insertIntoFibonaciHeap(heap, child);
			child = child->right;
		}
	}

	// 删除最小结点
	FibonaciNode *preMin = heap->min;
	heap->min = preMin->right;
	preMin->left->right = preMin->right;
	preMin->right->left = preMin->left;
	free(preMin);

	heap->num--;
	if (heap->num == 0)
	{
		// 堆为空
		heap->min = NULL;
	}
	else
	{
		// 合并根链表中度数相同的结点
		consolidate(heap);
	}
	
	return mini;
}
Example #15
0
/**
 * Delete the element associated with the lowest key and returns it
 * Cost: Worst case: O (n) ; Amortized: O(log n)
 * Pre: a fib_heap with n elems
 * Post: a fib_heap with n-1 elems where the removed elem was the min.key of previuos heap
**/
int fib_heap::deleteMin()
{
	if (this->isEmpty() ) {
		throw ("Trying to deleteMin in a empty heap");
	} else {
		node_t *min_out = min;
		int min_v = min_out->key;

		node_t *children_list = min_out->child;
		if (children_list != nullptr) {
			min_out->child = nullptr;
			min_out->degree = 0;

			//Setting parent for children to nullptr:
			node_t* aux = children_list;
			do {
				aux->parent = nullptr;
				aux = aux->right;
			} while (aux != children_list);

			//Append children_list to root list
			concatenate_circular_lists(root_list,children_list);
		}

		//Decrementing size of the fib heap
		--n;
		//Readjusting fib_heap according to the new structure and lost of min
		remove_from_list(root_list,min_out);

		if (n > 1)
			consolidate();

		delete min_out;
		return min_v;
	}
}
void* fibonacci_heap_extract_min(fibonacci_heap* heap)
{
    heap_node* z;
    heap_node* x;
    heap_node* tmp_right;
    heap_node* node_to_free;

    void* p_ret;
    size_t number_of_children;

    if (!heap) 
    {
        return NULL;
    }

    z = heap->minimum_node;

    if (!z) 
    {
        return NULL; /* Heap is empty. */
    }

    number_of_children = z->degree;
    x = z->child;

    while (number_of_children > 0) 
    {
        tmp_right = x->right;

        x->left->right = x->right;
        x->right->left = x->left;

        x->left = heap->minimum_node;
        x->right = heap->minimum_node->right;
        heap->minimum_node->right = x;
        x->right->left = x;

        x->parent = NULL;
        x = tmp_right;
        --number_of_children;
    }

    z->left->right = z->right;
    z->right->left = z->left;

    p_ret = heap->minimum_node->element;

    if (z == z->right)
    {
        node_to_free = heap->minimum_node;
        heap->minimum_node = NULL;
    }
    else 
    {
        node_to_free = heap->minimum_node;
        heap->minimum_node = z->right;
        consolidate(heap);
    }

    unordered_map_remove(heap->node_map, p_ret);
    free(node_to_free);
    return p_ret;
}
Example #17
0
int main (int argc, char *argv[]) {
	FILE		*imgfp;			/* input file */
	FILE		*outfp;			/* output file */

/*************/
/* image i/o */
/*************/
	char		*ptr, string[MAXL], program[MAXL], command[MAXL];
	char		imgroot[MAXL], imgfile[MAXL], ifhfile[MAXL]; 
	char		mskroot[MAXL], mskfile[MAXL]; 
	char		tmproot[MAXL], tmpfile[MAXL]; 
	char		trailer[MAXL] = "", outroot[MAXL], outfile[MAXL], recfile[MAXL];

/***************/
/* computation */
/***************/
	float		*imgv, *imgr, *imgm;
	float		v, frac, t, del2v, dmin;
	float		fndex[3], x[3], w[3], dvdx[3], d2vdx2[3];
	float		ctneg = 0.0, ctpos = 0.0;
	float		vtneg = 0.0, vtpos = 0.0;
	float		srad = 0.0, orad = 0;
	int		ix, iy, iz, dim, nx, ny, nz;
	int		c, i, j, k, l, jmin;
	int		isbig, isbigm;
	char		control = '\0';

/**************/
/* peak lists */
/**************/
	EXTREMUM	*ppos, *pneg, *pall, *pallN, ptmp[1];
	int		mpos = 0, mneg = 0, npos = 0, nneg = 0, nall, nallN, Nvoxcrit = 1;
	int		npos0, npos1, npos2;
	int		nneg0, nneg1, nneg2;

/*********/
/* flags */
/*********/
	int		mask = 0;
	int		status = 0;
	int		debug = 0;
	int		quiet = 0;
	int		forceblur = 0;
	
	printf ("%s\n", rcsid);
	if (!(ptr = strrchr (argv[0], '/'))) ptr = argv[0]; else ptr++;
	strcpy (program, ptr);

/******************************/
/* get command line arguments */
/******************************/
	for (k = 0, i = 1; i < argc; i++) {
		if (*argv[i] == '-') {
			strcpy (command, argv[i]); ptr = command;
			while (c = *ptr++) switch (c) {
				case 'q': quiet++;				break;
				case 'F': forceblur++;				break;
				case 's': srad = atof (ptr);			*ptr = '\0'; break;
				case 'd': dthresh = atof (ptr);			*ptr = '\0'; break;
				case 'n': ntop = atoi (ptr);			*ptr = '\0'; break;
				case 'N': Nvoxcrit = atoi (ptr);		*ptr = '\0'; break;
				case 'o': orad = atof (ptr);			*ptr = '\0'; break;
				case '@': control = *ptr++;			*ptr = '\0'; break;
				case 'c': getrange (ptr, &ctneg, &ctpos);	*ptr = '\0'; break;
				case 'v': getrange (ptr, &vtneg, &vtpos);	*ptr = '\0'; break;
				case 'm': getroot (ptr, mskroot); mask++;	*ptr = '\0'; break;
				case 'a': strncpy (trailer, ptr, MAXL - 1);	*ptr = '\0'; break;
			}
		} else switch (k) {
		 	case 0: getroot (argv[i], imgroot);	k++; break;
		}	
	}
	if (k < 1) {
		printf ("Usage: %s <file_4dfp>\n", program);
		printf (" e.g., %s grand_average_222[.4dfp.img] -s10\n", program);
		printf ("\toption\n");
		printf ("\t-s<flt>\tpreblur with hard sphere kernel of specified radius\n");
		printf ("\t-n<int>\tlimit initial pos and neg peak list lengths (default=%d)\n", NTOP);
		printf ("\t-c<flt>[to<flt>] specify sign inverted curvature thresholds (default none)\n");
		printf ("\t-v<flt>[to<flt>] specify peak value thresholds (default none)\n");
		printf ("\t-d<flt>\tconsolidate extremum pairs closer than specified distance\n");
		printf ("\t-o<flt>\toutput a fidl compatible 4dfp format ROI file with regions of specified radius\n");
		printf ("\t-m<str>\tapply named mask file to output ROIs\n");
		printf ("\t-N<int>\tspecify output ROI minimum voxel count (default = 1)\n");
		printf ("\t-a<str>\tappend specified string to ROI output filename\n");
		printf ("\t-q\tquiet mode (suppress rec file listing)\n");
		printf ("\t-F\tforce preblur image creation even if hsphere_4dfp result exists\n");
		printf ("\t-@<b|l>\toutput big or little endian (default input endian)\n");
		printf ("N.B.:\toperations controlled by options -s, -n, -c, -v, -d, -o, -m, -N are applied serially in listed order\n");
		printf ("N.B.:\tall distances are in mm\n");
		printf ("N.B.:\toption -s<flt> creates a blurred image by invoking hsphere_4dfp\n");
		printf ("N.B.:\toption -F is intended for use in iterative scripts and has no effect absent -s<flt>\n");
		exit (1);
	}

/************/
/* read ifh */
/************/
	sprintf (imgfile, "%s.4dfp.img", imgroot);
	if (srad > 0.0) {
		sprintf (tmproot, "%s_%.0fmm", imgroot, srad);
	} else {
		strcpy  (tmproot, imgroot);
	}
	sprintf (tmpfile, "%s.4dfp.img", tmproot);
	sprintf (ifhfile, "%s.4dfp.ifh", imgroot);

	fprintf (stdout, "Reading: %s\n", ifhfile);
	if (Getifh (ifhfile, &imgifh)) errr (program, ifhfile);
	isbig = strcmp (imgifh.imagedata_byte_order, "littleendian");
	if (!control) control = (isbig) ? 'b' : 'l';
	printf ("image dimensions \t%10d%10d%10d%10d\n",
		imgifh.matrix_size[0], imgifh.matrix_size[1], imgifh.matrix_size[2], imgifh.matrix_size[3]);
	printf ("image mmppix     \t%10.6f%10.6f%10.6f\n",
			imgifh.mmppix[0], imgifh.mmppix[1], imgifh.mmppix[2]);
	printf ("image center     \t%10.4f%10.4f%10.4f\n",
			imgifh.center[0], imgifh.center[1], imgifh.center[2]);
	printf ("image orientation\t%10d\n", imgifh.orientation);

/********************************************************************/
/* check that optionally specified mask is dimensionally consistent */
/********************************************************************/
	if (mask) {
		sprintf (mskfile, "%s.4dfp.img", mskroot);
		sprintf (ifhfile, "%s.4dfp.ifh", mskroot);
		fprintf (stdout, "Reading: %s\n", ifhfile);
		if (Getifh (ifhfile, &mskifh)) errr (program, ifhfile);
		isbigm = strcmp (mskifh.imagedata_byte_order, "littleendian");
		status = imgifh.orientation - mskifh.orientation;
		for (k = 0; k < 3; k++) {
			status |= imgifh.matrix_size[k] - mskifh.matrix_size[k];
			status |= (fabs ((double) (imgifh.mmppix[k] - mskifh.mmppix[k])) > 0.0001);
		}
		if (status) {
			fprintf (stderr, "%s: %s %s dimension mismatch\n", program, imgroot, mskroot);
			exit (-1);
		}
	}

	dim = 1; for (k = 0; k < 3; k++) dim *= imgifh.matrix_size[k];
	if (!(imgv = (float *) malloc (dim * sizeof (float)))) errm (program);
	if (!(imgr = (float *) malloc (dim * sizeof (float)))) errm (program);
	if (!(imgm = (float *) malloc (dim * sizeof (float)))) errm (program);
	nx = imgifh.matrix_size[0];
	ny = imgifh.matrix_size[1];
	nz = imgifh.matrix_size[2]; 

/*****************************************/
/* virtual flip instead of x4dfp2ecat () */
/*****************************************/
	vrtflip_ (&imgifh.orientation, imgifh.matrix_size, imgifh.center, imgifh.mmppix, centerr, mmppixr);
	printf ("atlas mmppix     \t%10.6f%10.6f%10.6f\n", mmppixr[0], mmppixr[1], mmppixr[2]); 
	printf ("atlas center     \t%10.4f%10.4f%10.4f\n", centerr[0], centerr[1], centerr[2]);

/****************************************************/
/* read filtered image or create using hpshere_4dfp */
/****************************************************/
	if (forceblur || access (tmpfile, R_OK)) {
		sprintf (command, "hsphere_4dfp %s %.4f", imgfile, srad);
		printf ("%s\n", command);
		if (system (command)) errw (program, tmpfile);
	}
	printf ("Reading: %s\n", tmpfile);
	if (!(imgfp = fopen (tmpfile, "rb")) || eread (imgv, dim, isbig, imgfp)
	|| fclose (imgfp)) errr (program, tmpfile);

/************************************************************************************************/
/* intial extremum memory allocation (realloc on unassigned pointer => unpredictable core dump) */
/************************************************************************************************/
	if (!(ppos = (EXTREMUM *) malloc ((mpos = MSIZE) * sizeof (EXTREMUM)))) errm (program);
	if (!(pneg = (EXTREMUM *) malloc ((mneg = MSIZE) * sizeof (EXTREMUM)))) errm (program);
/*******************/
/* compile extrema */
/*******************/
	printf ("peak value     thresholds %10.4f to %10.4f\n", vtneg, vtpos);
	printf ("peak curvature thresholds %10.4f to %10.4f\n", ctneg, ctpos);
	printf ("compiling extrema slice");
	for (iz = 1; iz < imgifh.matrix_size[2] - 1; iz++) {printf (" %d", iz + 1); fflush (stdout);
	for (iy = 1; iy < imgifh.matrix_size[1] - 1; iy++) {
	for (ix = 1; ix < imgifh.matrix_size[0] - 1; ix++) {
		i = ix + nx*(iy + ny*iz);
		dvdx[0] = 0.5*(-imgv[i - 1]	+ imgv[i + 1]);
		dvdx[1] = 0.5*(-imgv[i - nx]	+ imgv[i + nx]);
		dvdx[2] = 0.5*(-imgv[i - nx*ny]	+ imgv[i + nx*ny]);
		d2vdx2[0] = -2.0*imgv[i] + imgv[i - 1]		+ imgv[i + 1];
		d2vdx2[1] = -2.0*imgv[i] + imgv[i - nx]		+ imgv[i + nx];
		d2vdx2[2] = -2.0*imgv[i] + imgv[i - nx*ny]	+ imgv[i + nx*ny];
		for (k = 0; k < 3; k++) w[k] = -dvdx[k] / d2vdx2[k];
		for (del2v = k = 0; k < 3; k++) del2v += d2vdx2[k] / (mmppixr[k] * mmppixr[k]);
		fndex[0] = (float) (ix + 1) + w[0];
		fndex[1] = (float) (iy + 1) + w[1];
		fndex[2] = (float) (iz + 1) + w[2];
		for (k = 0; k < 3; k++) x[k] = fndex[k] * mmppixr[k] - centerr[k];

		if (imgv[i] > 0.0
		&& del2v <= -ctpos
		&& imgv[i] > imgv[i - 1]	&& imgv[i] > imgv[i + 1]
		&& imgv[i] > imgv[i - nx]	&& imgv[i] > imgv[i + nx]
		&& imgv[i] > imgv[i - nx*ny]	&& imgv[i] > imgv[i + nx*ny]) {
			imgvalx_ (imgv, &nx, &ny, &nz, centerr, mmppixr, x, &t, &l);
			if (l < 1) {printf ("undefined imgvalx point\n"); continue;}
			if (t < vtpos) continue;
			if (mpos <= npos) {
				mpos += MSIZE;
				if (!(ppos = (EXTREMUM *) realloc (ppos, mpos * sizeof (EXTREMUM)))) errm (program);
			}
			for (k = 0; k < 3; k++) ppos[npos].x[k] = x[k];
			ppos[npos].v = t;
			ppos[npos].del2v = del2v;
			ppos[npos].weight = 1.0;
			ppos[npos].nvox = ppos[npos].killed = 0;
			npos++;
		}

		if (imgv[i] < 0.0
		&& del2v >= -ctneg
		&& imgv[i] < imgv[i - 1]	&& imgv[i] < imgv[i + 1]
		&& imgv[i] < imgv[i - nx]	&& imgv[i] < imgv[i + nx]
		&& imgv[i] < imgv[i - nx*ny]	&& imgv[i] < imgv[i + nx*ny]) {
			imgvalx_ (imgv, &nx, &ny, &nz, centerr, mmppixr, x, &t, &l);
			if (l < 1) {printf ("undefined imgvalx point\n"); continue;}
			if (t > vtneg) continue;
			if (mneg <= nneg) {
				mneg += MSIZE;
				if (!(pneg = (EXTREMUM *) realloc (pneg, mneg * sizeof (EXTREMUM)))) errm (program);
			}
			for (k = 0; k < 3; k++) pneg[nneg].x[k] = x[k];
			pneg[nneg].v = t;
			pneg[nneg].del2v = del2v;
			pneg[nneg].weight = 1.0;
			pneg[nneg].nvox = pneg[nneg].killed = 0;
			nneg++;
		}
	}}}
	printf ("\n"); fflush (stdout);
	printf ("before sorting npos=%d nneg=%d\n", npos, nneg); npos0 = npos; nneg0 = nneg;

	qsort ((void *) ppos, npos, sizeof (EXTREMUM), pcompare);
	qsort ((void *) pneg, nneg, sizeof (EXTREMUM), pcompare);

	printf ("positive peaks\n");
	ntot = 0;
	peaklist (stdout, ppos, npos, 0); npos1 = ntot;
	if (dthresh > 0.0) consolidate (ppos, npos);

	printf ("negative peaks\n");
	ntot = 0;
	peaklist (stdout, pneg, nneg, 0); nneg1 = ntot;
	if (dthresh > 0.0) consolidate (pneg, nneg);

	printf ("final peak list\n");
	ntot = 0;
	peaklist (stdout, ppos, npos, 0);
	peaklist (stdout, pneg, nneg, 0);

/********************************************/
/* combine positive and negative peak lists */
/********************************************/
	if (!(pall = (EXTREMUM *) malloc (ntot * sizeof (EXTREMUM)))) errm (program);
	nall = 0;
	for (npos2 = i = 0; i < ntop && i < npos; i++) if (!ppos[i].killed) {pall[nall++] = ppos[i]; npos2++;}
	for (nneg2 = i = 0; i < ntop && i < nneg; i++) if (!pneg[i].killed) {pall[nall++] = pneg[i]; nneg2++;}
	assert (ntot == nall);
	free (ppos); free (pneg);

	if (orad == 0.0) goto DONE;
/***************************/
/* create output ROI image */
/***************************/
		printf ("Reading: %s\n", imgfile);
		if (!(imgfp = fopen (imgfile, "rb")) || eread (imgv, dim, isbig,  imgfp)
		|| fclose (imgfp)) errr (program, imgfile);
	if (mask) {
		printf ("Reading: %s\n", mskfile);
		if (!(imgfp = fopen (mskfile, "rb")) || eread (imgm, dim, isbigm, imgfp)
		|| fclose (imgfp)) errr (program, mskfile);
	}

/****************************/
/* count voxels in each ROI */
/****************************/
	for (iz = 0; iz < imgifh.matrix_size[2]; iz++) {
	for (iy = 0; iy < imgifh.matrix_size[1]; iy++) {
	for (ix = 0; ix < imgifh.matrix_size[0]; ix++) {
		i = ix + nx*(iy + ny*iz);
		fndex[0] = (float) (ix + 1);
		fndex[1] = (float) (iy + 1);
		fndex[2] = (float) (iz + 1);
		for (k = 0; k < 3; k++) ptmp[0].x[k] =  fndex[k]*mmppixr[k] - centerr[k];
		dmin = 1.e6;
		for (j = 0; j < nall; j++) {
			t = (float) pdist (ptmp, pall + j);
			if (t < dmin) {
				jmin = j;
				dmin = t;
			}
		}
		k = !mask || (fabs (imgm[i]) > 1.e-37);
		if (k && (dmin < orad)) pall[jmin].nvox++;
	}}}

/*******************************/
/* apply voxel count criterion */
/*******************************/
	for (i = 0; i < ntot; i++) if (pall[i].nvox < Nvoxcrit) pall[i].killed = 1;
	if (!(pallN = (EXTREMUM *) malloc (ntot * sizeof (EXTREMUM)))) errm (program);
	for (nallN = i = 0; i < ntot; i++) if (!pall[i].killed) pallN[nallN++] = pall[i];
	free (pall);

	printf ("creating ROI slice");
	for (iz = 0; iz < imgifh.matrix_size[2]; iz++) {printf (" %d", iz + 1); fflush (stdout);
	for (iy = 0; iy < imgifh.matrix_size[1]; iy++) {
	for (ix = 0; ix < imgifh.matrix_size[0]; ix++) {
		i = ix + nx*(iy + ny*iz);
		imgr[i] = 0.0;
		fndex[0] = (float) (ix + 1);
		fndex[1] = (float) (iy + 1);
		fndex[2] = (float) (iz + 1);
		for (k = 0; k < 3; k++) ptmp[0].x[k] =  fndex[k]*mmppixr[k] - centerr[k];
		dmin = 1.e6;
		for (j = 0; j < nallN; j++) {
			t = (float) pdist (ptmp, pallN + j);
			if (t < dmin) {
				jmin = j;
				dmin = t;
			}
		}
		k = !mask || (fabs (imgm[i]) > 1.e-37);
		if (k && (dmin < orad)) imgr[i] = jmin + 2;
	}}}
	printf ("\n"); fflush (stdout);

	if (!(ptr = strrchr (imgroot, '/'))) ptr = imgroot; else ptr++;
	if (strlen (trailer)) {
		sprintf (outroot, "%s_ROI_%s", ptr, trailer);
	} else {
		sprintf (outroot, "%s_ROI", ptr);
	}
	sprintf (outfile, "%s.4dfp.img", outroot);
	printf ("Writing: %s\n", outfile);
	if (!(outfp = fopen (outfile, "wb")) || ewrite (imgr, dim, control, outfp)
	|| fclose (outfp)) errw (program, outfile);

/********************************************/
/* output ROI ifh and make analyze hdr file */
/********************************************/
	if (Writeifh (program, outfile, &imgifh, control)) errw (program, outroot);
	sprintf (outfile, "%s.4dfp.ifh", outroot);
	if (!(outfp = fopen (outfile, "a"))) errw (program, outfile);
	for (i = 0; i < nallN; i++) {
		fprintf (outfp, "region names\t:= %-5droi_%+03d_%+03d_%+03d%10d\n", i,
			nint (pallN[i].x[0]), nint (pallN[i].x[1]), nint (pallN[i].x[2]), pallN[i].nvox);
	}
	fclose (outfp);

/********************/
/* make analyze hdr */
/********************/
	sprintf (command, "ifh2hdr %s -r%d", outroot, nallN + 1);
	printf ("%s\n", command); status |= system (command);

/******************/
/* output ROI rec */
/******************/
	sprintf   (outfile, "%s.4dfp.img", outroot);
	startrece (outfile, argc, argv, rcsid, control);
	sprintf   (recfile, "%s.rec", outfile);
	if (!(outfp = fopen (recfile, "a"))) errw (program, recfile);
	fprintf (outfp, "Peak value     thresholds %10.4f to %10.4f\n", vtneg, vtpos);
	fprintf (outfp, "Peak curvature thresholds %10.4f to %10.4f\n", ctneg, ctpos);
	fprintf (outfp, "Peak counts before sorting pos=%d neg=%d\n", npos0, nneg0);
	fprintf (outfp, "Peak counts after  sorting pos=%d neg=%d\n", npos1, nneg1);
	fprintf (outfp, "Peak counts after %.4f mm threshold consolidation pos=%d neg=%d\n", dthresh, npos2, nneg2);
	ntot = 0; peaklist (outfp, pallN, nallN, 1);
	free (pallN);
	fprintf (outfp, "N.B.: indices count from 1 and include orientation specific 4dfptoanalyze flips\n");
	fclose (outfp);
	catrec (tmpfile);
	if (mask) catrec (mskfile);
	endrec ();
	sprintf (command, "brec %s -2", recfile); if (!quiet) system (command);

DONE:	free (imgv); free (imgr); free (imgm);
	exit (status);
}
Example #18
0
void do_label( char_data* ch, char* argument )
{
  char        arg  [ MAX_INPUT_LENGTH ];
  obj_data*   obj;
  char*     label;
  bool     remove;

  remove = !contains_word( argument, "as", arg );

  if( *argument == '\0' || ( !remove && *arg == '\0' ) ) {
    send( ch, "Label what item and as what?\r\n" );
    return;
    }

  if( ( obj = one_object( ch, remove ? argument : arg,
    "label", &ch->contents ) ) == NULL ) 
    return;

  if( remove ) {
    if( obj->label == empty_string ) {
      send( ch, "%s isn't labeled.\r\n", obj );
      return;
      }
    free_string( obj->label, MEM_OBJECT );
    obj->label = empty_string;
    send( ch, "You remove the label from %s.\r\n", obj );
    return;
    }

  if( obj->pIndexData->item_type != ITEM_CONTAINER ) {
    send( ch, "You may only label containers.\r\n" );
    return;
    }

  if( ( label = obj->label ) != empty_string ) {
    obj->label = empty_string;
    send( ch, "%s is already labeled as '%s'.\r\n", obj, label );
    obj->label = label;
    return;
    }

  if( !valid_label( ch, argument ) )
    return;

  if( obj->number > 1 ) {
    obj->number--;
    obj = duplicate( obj );
    }
 
  if( obj->label == empty_string ) {
    send( ch, "You label %s '%s'.\r\n", obj, argument );
    }
  else {
    free_string( obj->label, MEM_OBJECT );
    obj->label = empty_string;
    fsend( ch,
      "You remove the old label from %s and replace it with '%s'.\r\n", 
      obj, argument );
    }

  obj->label = alloc_string( argument, MEM_OBJECT );

  if( obj->array == NULL ) 
    obj->To( ch );

  consolidate( obj );
}
Example #19
0
void do_repair( char_data* ch, char* argument )
{
  char           buf  [ MAX_INPUT_LENGTH ];
  char_data*  keeper;
  obj_data*      obj;
  int           cost;
  int           cond;

  if( *argument == '\0' ) {
    send( ch, "Repair what?\r\n" );
    return;
    }

  if( ( keeper = find_keeper( ch ) ) == NULL )
    return;

  if( keeper->pShop->repair == 0 ) {
    process_tell( keeper, ch, "Sorry - I do not repair items." );
    return;
    }

  if( ( obj = one_object( ch, argument, "repair", &ch->contents ) ) == NULL ) 
    return;

  if( !obj->droppable( ) ) {
    send( ch, "You can't let go of %s.\r\n", obj );
    return;
    }

  if( ( cost = repair_cost( keeper, obj ) ) <= 0 ) {
    process_tell( keeper, ch, "That isn't something I can repair" );
    return;
    }

  if( ( cond = repair_condition( obj ) ) < 0 ) {
    process_tell( keeper, ch,
      "That item is too old to be worth repairing." );
    return;
    }

  if( !obj->Damaged( ) ) {
    process_tell( keeper, ch,
      "That isn't damaged enough to be worth repairing." );
    return;
    }

  sprintf( buf, "%s repairs %s for you at a cost of",
    keeper->Name( ch ), obj->Seen_Name( ch ) );
  *buf = toupper( *buf );
  if( !remove_coins( ch, cost, buf ) ) {
    sprintf( buf, "You can't afford the cost of repairing %s.", 
      obj->Seen_Name( ch ) );
    process_tell( keeper, ch, buf );   
    return;
    }
    
  fsend( ch, "%s gets %s repaired.\r\n", ch, obj );

  obj = (obj_data*) obj->From( 1 );

  obj->age       += int( 1+obj->rust*pow(cond-obj->condition,1.5)/100. );
  obj->condition  = cond;

  obj->To( &ch->contents );
  consolidate( obj );
}
Example #20
0
bool remove_coins( char_data* ch, int amount, char* message ) 
{
  obj_data*       obj;
  obj_data*  coin_obj  [ 4 ];
  int           coins  [ 4 ];
  bool           flag  = FALSE;
  int             dum;
  int          number  [] = { 0, 0, 0, 0 };
  int             pos  [ MAX_COIN ];
  int             neg  [ MAX_COIN ];
  int               i;

  vzero( coin_obj, MAX_COIN );
  vzero( coins,    MAX_COIN );
  vzero( number,   MAX_COIN );   

  for( i = 0; i < ch->contents; i++ ) {
    obj = (obj_data*) ch->contents[i];
    for( int j = 0; j < MAX_COIN; j++ ) 
      if( obj->pIndexData->vnum == coin_vnum[j] ) {
        coin_obj[j] = obj; 
        coins[j] = obj->number;
        }
    }
 
  for( i = 0; i < MAX_COIN && amount > 0; i++ ) {
    amount -= coins[i]*coin_value[i];
    number[i] = coins[i];
    }

  if( amount > 0 ) 
    return FALSE;

  amount = -amount;
   
  for( i--; i >= 0; i-- ) {
    dum = amount/coin_value[i];
    amount -= dum*coin_value[i];
    number[i] -= dum;
    }
    
  for( i = MAX_COIN - 1; i >= 0; i-- ) {
    if( number[i] > 0 )
      coin_obj[i]->Extract( number[i] );
    pos[i] = max( 0, number[i] );
    neg[i] = max( 0, -number[i] );
    if( neg[i] != 0 ) {
      if( coin_obj[i] == NULL ) {
        obj = create( get_obj_index( coin_vnum[i] ), neg[i] );
        obj->To( ch );
        consolidate( obj );
        }
      else
        coin_obj[i]->number += neg[i];
      flag = TRUE;
      }
    }

  if( message != NULL ) {
    fsend( ch, "%s%s.\r\n", message, coin_phrase( pos ) );
    if( flag ) 
      send( ch, "You receive%s in change.\r\n", coin_phrase( neg ) );
    }

  return TRUE;
}
Example #21
0
 void dump_as_list(const int fd) final {
     consolidate();
     m_main.dump_as_list(fd);
 }
Example #22
0
void do_skin( char_data* ch, char* argument )
{
  mprog_data*         mprog;
  obj_data*          corpse;
  thing_data*         thing;
  thing_array*         list;
  species_data*     species;
  char_data*            rch;
  int i;

  if( is_confused_pet( ch ) )
    return;

  if( ( thing = one_thing( ch, argument,
    "skin", ch->array ) ) == NULL )
    return;

  if( ( corpse = object( thing ) ) == NULL ) {
    fsend( ch, "Skinning %s alive would be cruel and unusual.\r\n", thing );
    return;
    } 

  if( corpse->pIndexData->item_type != ITEM_CORPSE ) {
    send( ch, "You can only skin corpses.\r\n" );
    return;
    }

  if( corpse->pIndexData->vnum == OBJ_CORPSE_PC ) {
    send( ch, "You can't [yet] skin player corpses!\r\n" );
    return;
    }

  if( ( species = get_species( corpse->value[1] ) ) == NULL ) {
    send( ch, "Corpses without a species cannot be skinned.\r\n" );
    return;
    }

  for( mprog = species->mprog; mprog != NULL; mprog = mprog->next )
    if( mprog->trigger == MPROG_TRIGGER_SKIN ) {
      var_obj  = corpse;
      var_ch   = ch;    
      var_room = ch->in_room;
      execute( mprog ); 
      return;
      }

  list = get_skin_list( species );

  if( list == (thing_array*) -1 ) {
    send( ch, "You cannot skin %s.\r\n", corpse );
    return;
    }

  if( list == NULL ) {
    fsend( ch, "You skin %s, but it is too mangled to be of any use.",
      corpse );
    fsend( *ch->array,
      "%s skins %s but is unable to extract anything of value.",
      ch, corpse );
    }
  else {
    fsend( ch,
      "You skin %s producing %s.\r\n",
      corpse, list );

    for( i = 0; i < *ch->array; i++ )  
      if( ( rch = character( ch->array->list[i] ) ) != NULL
         && rch != ch && ch->Seen( rch ) )
         fsend( rch,
           "%s skins %s producing %s.\r\n",
           ch, corpse, list );

    for( i = 0; i < *list; i++ ) {
      list->list[i]->To( ch );
      consolidate( (obj_data*) list->list[i] );
      }

    delete list;
    }
  
  drop_contents( corpse ); 
  corpse->Extract( 1 );
}
/*
 *--------------------------------------------------------------------------------------
 *       Class:  RTree::Trunk
 *      Method:  RTree::Trunk :: overflow
 * Description:  
 *     when a node has too many children it calls it call's it's parent's overflow function
 *     the parent then redistributes it's grand children amoungst it's children and if there are
 *     too many grandchildren it spawns a new child and inserts it into itself
 *     if the parent has too many children it will then propogate the overflow
 *
 *--------------------------------------------------------------------------------------
 */
void RTree::Trunk::overflow( Node *new_node ) {
    Dynamic_array<RTree::Node*> cousin_nodes;

    // gather up a list of all the grandchildren
    int children_list_size;
    for( int i = 0; i < num_children; ++i ) {
        Node **adopted_children = children[i]->adopt_children( children_list_size );
        cousin_nodes.add( adopted_children, children_list_size ); 
        //delete[] adopted_children;
    };

    // add in the shape causing the overflow
    cousin_nodes.add( new_node );

    // sort them according to their hilbert values
    cousin_nodes.sort( less_than );

    int size = cousin_nodes.get_size();

    // check if there is enough room available to just shift the leaves around
    if( num_children * max_children < size ) { // if there is not then make more room
        Node *new_child;
        switch( children[0]->check_type() ) {
        case node_leaf_t:
            new_child = new Branch();
            break;
        case node_branch_t:
            new_child = new Branch();
            break;
        case node_trunk_t:
            new_child = new Trunk();
            break;
        default:
            return;
        }

        // add the leaves all into the children and the new node
        int leaves_per;
        if( size % (num_children+1) == 0 ) {            // if the nodes can now be split in evenly ex) 9 amoungst 3
            leaves_per = (size / (num_children + 1));   // then do so
        } else {                                        // otherwise we need to add 1 to account for the remainder
            leaves_per = (size / (num_children+1)) + 1; // ex) 8 amoungst 3 results in 3 leaves per for the first 2
        }                                               //     and 2 for the newly added child

        int i = 0;
        int k = 0;
        for( ; k < (num_children * leaves_per); ) {     // add most of the leaves into the children
            children[i]->insert( cousin_nodes[k] );
            ++k;
            if( k % leaves_per == 0 ) {
                ++i;
            }
        }

        for( ; k < size; ++k ) {                        // add the remainder into the new node
            new_child->insert( cousin_nodes[k] );
        }

        bounds.invalidate();

        // if the current node is full this insert will propogate the overflow
        this->insert( new_child );
        consolidate();

    } else {

        // no split was needed so just redistribute the leaves
        // add the leaves all into the children
        //int leaves_per = size / num_children;
        int leaves_per;
        if( size % num_children == 0 ) {            // if the nodes can now be split in evenly ex) 9 amoungst 3
            leaves_per = (size / num_children);   // then do so
        } else {                                        // otherwise we need to add 1 to account for the remainder
            leaves_per = (size / (num_children+1)) + 1; // ex) 8 amoungst 3 results in 3 leaves per for the first 2
        }                                               //     and 2 for the newly added child
        int i = 0;
        int k = 0;
        for( ; k < ((num_children - 1) * leaves_per); ) {     // add most of the leaves into the children
            children[i]->insert( cousin_nodes[k] );
            ++k;
            if( k % leaves_per == 0 ) {
                ++i;
            }
        }

        for( ; k < size; ++k ) {                        // add the remainder into the new node
            children[i]->insert( cousin_nodes[k] );
        }
/*
        int i = 0;
        for( int k = 0; k < size; ) {
            children[i]->insert( cousin_nodes[k] );
            ++k;
            if( k % leaves_per == 0 ) {
                ++i;
            }
        }
*/

        bounds.invalidate();

        // TODO look into a better method of consolidation
        // it doesn't need to be done as frequently as it is
        consolidate();
	}
}		/* -----  end of method RTree::Trunk::overflow  ----- */
Example #24
0
 void dump_as_list(int fd) {
     consolidate();
     m_main.dump_as_list(fd);
 }
Example #25
0
//==============================================================================
void CommandInstance::consolidateUndoRedoData(CommandInstance* parentInstance)
{
	if (parentInstance == nullptr)
	{
		for (auto& data : undoRedoData_)
		{
			auto reflectionUndoRedoData = dynamic_cast<ReflectionUndoRedoData*>(data.get());
			if (reflectionUndoRedoData != nullptr)
			{
				reflectionUndoRedoData->consolidate();
			}
		}
		return;
	}

	auto lastParent = parentInstance->undoRedoData_.empty() ?
	nullptr :
	dynamic_cast<ReflectionUndoRedoData*>(parentInstance->undoRedoData_.back().get());
	if (lastParent != nullptr)
	{
		if (lastParent->undoRedoHelperList_.size() == 1 && lastParent->undoRedoHelperList_[0]->isMethod())
		{
			lastParent = nullptr;
		}
	}

	auto firstChild =
	undoRedoData_.empty() ? nullptr : dynamic_cast<ReflectionUndoRedoData*>(undoRedoData_.front().get());
	if (firstChild != nullptr)
	{
		if (firstChild->undoRedoHelperList_.size() == 1 && firstChild->undoRedoHelperList_[0]->isMethod())
		{
			firstChild = nullptr;
		}
	}

	if (lastParent != nullptr && firstChild != nullptr)
	{
		for (auto& childHelper : firstChild->undoRedoHelperList_)
		{
			auto it =
			std::find_if(lastParent->undoRedoHelperList_.begin(), lastParent->undoRedoHelperList_.end(),
			             [&childHelper](std::unique_ptr<RPURU::ReflectedClassMemberUndoRedoHelper>& item) {
				             return childHelper->objectId_ == item->objectId_ && childHelper->path_ == item->path_;
				         });
			if (it != lastParent->undoRedoHelperList_.end())
			{
				auto& helper = *it;
				TF_ASSERT(!helper->isMethod());
				TF_ASSERT(!childHelper->isMethod());
				auto propertyHelper = static_cast<RPURU::ReflectedPropertyUndoRedoHelper*>(helper.get());
				auto childPropertyHelper = static_cast<RPURU::ReflectedPropertyUndoRedoHelper*>(childHelper.get());
				propertyHelper->postValue_ = childPropertyHelper->postValue_;
			}
			else
			{
				TF_ASSERT(!childHelper->isMethod());
				lastParent->undoRedoHelperList_.emplace_back(childHelper.release());
			}
		}
		undoRedoData_.erase(undoRedoData_.begin());
	}

	for (auto& data : undoRedoData_)
	{
		parentInstance->undoRedoData_.emplace_back(data.release());
	}
	undoRedoData_.clear();
}
int main(int argc,char *argv[]) {

	QCoreApplication app(argc,argv); //important for qApp->applicationDirPath() in processtracker

//	test_armadillo();
//	test_pca_2();
//	return 0;

	CLParams CLP;
	QStringList required;
	CLP=get_command_line_params(argc,argv,required);

	ProcessTracker PT;
	register_processors(PT);

	if (CLP.unnamed_parameters.count()>1) {
		printf("Only one command parameter may be specified.\n");
		return -1;
	}

	QString command=CLP.unnamed_parameters.value(0);

	if (command.isEmpty()) {
		printf("\nmountainsort processors:\n");
		for (int i=0; i<PT.processorCount(); i++) {
			QString cmd=PT.processor(i).command;
			printf("%s ",cmd.toLatin1().data());
		}
		printf("\n\n");
		return -1;
	}

	PTProcessor PP=PT.findProcessor(command);
	printf("%s version %s\n",PP.command.toLatin1().data(),PP.version.toLatin1().data());

	if (!CLP.named_parameters.value("force").toInt()) {
		if (PT.processAlreadyCompleted(CLP)) {
			printf("Process already completed.\n");
			return 0;
		}
	}
	CLP.named_parameters.remove("force");

	QTime timer; timer.start();

	if (command=="extract") {
		QString input_path=CLP.named_parameters["input"];
		QString output_path=CLP.named_parameters["output"];
		int num_channels=CLP.named_parameters["num_channels"].toInt();
		long t1=CLP.named_parameters["t1"].toLong();
		long t2=CLP.named_parameters["t2"].toLong();
		QStringList channels_str=CLP.named_parameters["channels"].split(",");
		int M=channels_str.count();
		int channels[M];
		for (int m=0; m<M; m++) channels[m]=channels_str[m].toInt();

		if ((input_path.isEmpty())||(output_path.isEmpty())) {extract_usage(); return -1;}
		if (M==0) {extract_usage(); return -1;}

		if (!extract(input_path.toLatin1().data(),output_path.toLatin1().data(),num_channels,M,channels,t1,t2)) {
			printf("Error in extract.\n");
			return -1;
		}
	}
	else if (command=="bandpass_filter") {
		QString input_path=CLP.named_parameters["input"];
		QString output_path=CLP.named_parameters["output"];
		double samplefreq=CLP.named_parameters["samplefreq"].toDouble();
		double freq_min=CLP.named_parameters["freq_min"].toDouble();
		double freq_max=CLP.named_parameters["freq_max"].toDouble();
		double outlier_threshold=CLP.named_parameters["outlier_threshold"].toDouble();

		if ((input_path.isEmpty())||(output_path.isEmpty())) {bandpass_filter_usage(); return -1;}
		if ((samplefreq==0)||(freq_min==0)||(freq_max==0)) {bandpass_filter_usage(); return -1;}

		if (!bandpass_filter(input_path.toLatin1().data(),output_path.toLatin1().data(),samplefreq,freq_min,freq_max,outlier_threshold)) {
			printf("Error in bandpass_filter.\n");
			return -1;
		}
	}
	else if (command=="normalize_channels") {
		QString input_path=CLP.named_parameters["input"];
		QString output_path=CLP.named_parameters["output"];

		if ((input_path.isEmpty())||(output_path.isEmpty())) {normalize_channels_usage(); return -1;}

		if (!normalize_channels(input_path.toLatin1().data(),output_path.toLatin1().data())) {
			printf("Error in normalize_channels.\n");
			return -1;
		}
	}
	else if (command=="whiten") {
		QString input_path=CLP.named_parameters["input"];
		QString output_path=CLP.named_parameters["output"];
		int ncomp=CLP.named_parameters["ncomp"].toInt();

		if ((input_path.isEmpty())||(output_path.isEmpty())) {whiten_usage(); return -1;}
		if (ncomp==0) {whiten_usage(); return -1;}

		if (!whiten(input_path.toLatin1().data(),output_path.toLatin1().data(),ncomp)) {
			printf("Error in whiten.\n");
			return -1;
		}
	}
	else if (command=="detect") {
		QString input_path=CLP.named_parameters["input"];
		QString output_path=CLP.named_parameters["output"];
		int inner_window_width=CLP.named_parameters["inner_window_width"].toInt();
		int outer_window_width=CLP.named_parameters["outer_window_width"].toInt();
		float threshold=CLP.named_parameters["threshold"].toFloat();

		if ((input_path.isEmpty())||(output_path.isEmpty())) {detect_usage(); return -1;}
		if (inner_window_width==0) {detect_usage(); return -1;}
		if (outer_window_width==0) {detect_usage(); return -1;}
		if (threshold==0) {detect_usage(); return -1;}

		if (!detect(input_path.toLatin1().data(),output_path.toLatin1().data(),inner_window_width,outer_window_width,threshold)) {
			printf("Error in detect.\n");
			return -1;
		}
	}
    else if (command=="features") {
        QString input_path=CLP.named_parameters["input"];
        QString detect_path=CLP.named_parameters["detect"];
        QString adjacency_path=CLP.named_parameters["adjacency"];
        QString output_path=CLP.named_parameters["output"];
        int num_features=CLP.named_parameters["num_features"].toInt();
        int clip_size=CLP.named_parameters["clip_size"].toInt();

        if ((input_path.isEmpty())||(detect_path.isEmpty())||(adjacency_path.isEmpty())||(output_path.isEmpty())) {features_usage(); return -1;}
        if (num_features==0) {features_usage(); return -1;}
        if (clip_size==0) {features_usage(); return -1;}

        if (!features(input_path.toLatin1().data(),detect_path.toLatin1().data(),adjacency_path.toLatin1().data(),output_path.toLatin1().data(),num_features,clip_size)) {
            printf("Error in features.\n");
            return -1;
        }
    }
    else if (command=="cluster") {
        QString input_path=CLP.named_parameters["input"];
        QString output_path=CLP.named_parameters["output"];

        if ((input_path.isEmpty())||(output_path.isEmpty())) {cluster_usage(); return -1;}

        if (!cluster(input_path.toLatin1().data(),output_path.toLatin1().data())) {
            printf("Error in cluster.\n");
            return -1;
        }
    }
	else if (command=="split_clusters") {
		QString input_path=CLP.named_parameters["input"];
		QString cluster_path=CLP.named_parameters["cluster"];
		QString output_path=CLP.named_parameters["output"];
		int num_features=CLP.named_parameters["num_features"].toInt();
		int clip_size=CLP.named_parameters["clip_size"].toInt();

		if ((input_path.isEmpty())||(cluster_path.isEmpty())||(output_path.isEmpty())) {cluster_usage(); return -1;}
		if (num_features==0) {cluster_usage(); return -1;}
		if (clip_size==0) {cluster_usage(); return -1;}

		if (!split_clusters(input_path.toLatin1().data(),cluster_path.toLatin1().data(),output_path.toLatin1().data(),num_features,clip_size)) {
			printf("Error in cluster.\n");
			return -1;
		}
	}
    else if (command=="templates") {
        QString input_path=CLP.named_parameters["input"];
        QString cluster_path=CLP.named_parameters["cluster"];
        QString output_path=CLP.named_parameters["output"];
        int clip_size=CLP.named_parameters["clip_size"].toInt();

        if ((input_path.isEmpty())||(output_path.isEmpty())) {templates_usage(); return -1;}
        if (clip_size==0) {templates_usage(); return -1;}

        if (!templates(input_path.toLatin1().data(),cluster_path.toLatin1().data(),output_path.toLatin1().data(),clip_size)) {
            printf("Error in templates.\n");
            return -1;
        }
    }
    else if (command=="consolidate") {
        QString cluster_path=CLP.named_parameters["cluster"];
        QString templates_path=CLP.named_parameters["templates"];
        QString cluster_out_path=CLP.named_parameters["cluster_out"];
        QString templates_out_path=CLP.named_parameters["templates_out"];
        QString load_channels_out_path=CLP.named_parameters["load_channels_out"];

        if ((cluster_path.isEmpty())||(templates_path.isEmpty())) {consolidate_usage(); return -1;}
        if ((cluster_out_path.isEmpty())||(templates_out_path.isEmpty())) {consolidate_usage(); return -1;}
        if (load_channels_out_path.isEmpty()) {consolidate_usage(); return -1;}

        if (!consolidate(cluster_path.toLatin1().data(),templates_path.toLatin1().data(),cluster_out_path.toLatin1().data(),templates_out_path.toLatin1().data(),load_channels_out_path.toLatin1().data())) {
            printf("Error in consolidate.\n");
            return -1;
        }
    }
    else if (command=="fit") {
        QString input_path=CLP.named_parameters["input"];
        QString cluster_path=CLP.named_parameters["cluster"];
        QString templates_path=CLP.named_parameters["templates"];
        QString cluster_out_path=CLP.named_parameters["cluster_out"];

        if ((input_path.isEmpty())||(cluster_path.isEmpty())||(templates_path.isEmpty())) {fit_usage(); return -1;}
        if ((cluster_out_path.isEmpty())) {fit_usage(); return -1;}

        if (!fit(input_path.toLatin1().data(),templates_path.toLatin1().data(),cluster_path.toLatin1().data(),cluster_out_path.toLatin1().data())) {
            printf("Error in fit.\n");
            return -1;
        }
    }
	else if (command=="extract_clips") {
		QString input_path=CLP.named_parameters["input"];
		QString cluster_path=CLP.named_parameters["cluster"];
		QString output_path=CLP.named_parameters["output"];
		QString index_out_path=CLP.named_parameters["index_out"];
		int clip_size=CLP.named_parameters["clip_size"].toInt();

		if ((input_path.isEmpty())||(cluster_path.isEmpty())) {extract_usage(); return -1;}
		if ((output_path.isEmpty())||(index_out_path.isEmpty())) {extract_usage(); return -1;}

		if (!extract_clips(input_path.toLatin1().data(),cluster_path.toLatin1().data(),output_path.toLatin1().data(),index_out_path.toLatin1().data(),clip_size)) {
			printf("Error in extract_clips.\n");
			return -1;
		}
	}
	else {
		printf("Unknown command: %s\n",command.toLatin1().data());
		return -1;
	}

	PT.reportProcessCompleted(CLP);

	printf("Elapsed time for %s: %.2f seconds\n",command.toLatin1().data(),timer.elapsed()*1.0/1000);

	return 0;
}
Example #27
0
File: FibHeap.cpp Project: cran/CRF
FibHeapNode *FibHeap::extractMin()
{
  FibHeapNode *Result;
  FibHeap *m_childHeap = NULL;
  
  // Remove minimum node and set m_min_root to next node
  
  if ((Result = minimum()) == NULL) return NULL;
  
  m_min_root = Result->m_right;
  Result->m_right->m_left = Result->m_left;
  Result->m_left->m_right = Result->m_right;
  Result->m_left = Result->m_right = NULL;
  
  m_num_nodes --;
  if (Result->m_mark) {
    m_num_marked_nodes --;
    Result->m_mark = 0;
  }
  Result->m_degree = 0;
  
  // Attach m_child list of Minimum node to the root list of the heap
  // If there is no m_child list, then do no work
  
  if (Result->m_child == NULL) {
    if (m_min_root == Result) m_min_root = NULL;
  }
  
  // If m_min_root==Result then there was only one root tree, so the
  // root list is simply the m_child list of that node (which is
  // NULL if this is the last node in the list)
  
  else if (m_min_root == Result) {
    m_min_root = Result->m_child;
  }
  
  // If m_min_root is different, then the m_child list is pushed into a
  // new temporary heap, which is then merged by Union() onto the
  // root list of this heap.
  
  else {
    m_childHeap = new FibHeap();
    m_childHeap->m_min_root = Result->m_child;
  }
  
  // Complete the disassociation of the Result node from the heap
  
  if (Result->m_child != NULL)
    Result->m_child->m_parent = NULL;
  Result->m_child = Result->m_parent = NULL;
  
  // If there was a m_child list, then we now merge it with the
  //	rest of the root list
  
  if (m_childHeap) makeUnion(m_childHeap);
  
  // Consolidate heap to find new minimum and do reorganize work
  
  if (m_min_root != NULL) consolidate();
  
  // Return the minimum node, which is now disassociated with the heap
  // It has m_left, m_right, m_parent, m_child, m_mark and m_degree cleared.
  
  return Result;
}
Example #28
0
void MatchDistribution::consolidate(const std::vector<MatchDistribution> &matchDistributionList)
{
    BOOST_FOREACH(const MatchDistribution &matchDistribution, matchDistributionList)
    {
        consolidate(matchDistribution);
    }
Example #29
0
unsigned int pq_extract(struct priority_queue *p){
	if(p->root_list != NULL){
		int temp;
		struct node *tempptr,*t1,*t2;
		temp = p->root_list->key;
		if((p->root_list->child == NULL) && (p->n_nodes == 1)){
			put_node(p->root_list);
			p->n_nodes = 0;
			p->root_list = NULL;
		}
		else if ((p->root_list->child == NULL) && (p->n_nodes > 1)){	
			p->root_list->left->right = p->root_list->right;
			p->root_list->right->left = p->root_list->left;
			tempptr = p->root_list;
			p->root_list = p->root_list->left;
			put_node(tempptr);
			p->n_nodes -= 1;
			if(p->root_list->key != 3)
				consolidate(p);
		}
		else if(p->root_list->child != NULL){
			t1 = p->root_list->child;
			while(t1 != t1->right ){
				t2=t1->right;
				t1->right = t2->right;
				t2->right->left = t1;
			
				t2->right= p->root_list->right;
				t2->left = p->root_list;
				t2->parent=NULL;
				t2->tag = 0;

				p->root_list->right->left = t2;
				p->root_list->right = t2;
				p->n_nodes += 1;
			}
				t1->right= p->root_list->right;
				t1->left = p->root_list;
				t1->parent = 0;
				t1->tag = 0;
				p->root_list->right->left = t1;
				p->root_list->right = t1;
				p->n_nodes += 1;
				p->root_list->degree = 0;
				t2 = p->root_list;
				p->root_list->left->right = p->root_list->right;
				p->root_list->right->left = p->root_list->left;
				p->root_list = p->root_list->right;
				put_node(t2);
				p->n_nodes -=1;
				consolidate(p);
		}
		return temp;
	}
	#ifdef DEBUG
	else{
		printf("priority_queue is Empty.\n");
		return -1;
	}
	#endif
}
void consolidate_complex_tracks(track_file_handle_t *t_handle,
				storm_status_t *storms1,
				storm_status_t *storms2,
				si32 nstorms1,
				si32 nstorms2,
				track_utime_t *track_utime)
     
{

  int i, jstorm, kstorm;
  si32 min_complex;
  storm_status_t *storm;
  track_match_t *match;
  /*
   * initialize storms2 array for checking
   */
  
  storm = storms2;
  for (jstorm = 0; jstorm < nstorms2; jstorm++, storm++) {
    storm->checked = FALSE;
  }
  
  /*
   * loop through each storm2 entry
   */
  
  storm = storms2;
  for (jstorm = 0; jstorm < nstorms2; jstorm++, storm++) {
    
    if (!storm->checked &&
	(storm->has_merger || storm->has_split)) {
      
      storm->checked = TRUE;
      N_complex_nums = 0;
      
      match = storm->match_array;
      for (kstorm = 0; kstorm < storm->n_match; kstorm++, match++) {

	/*
	 * search recursively to find all complex tracks in the
	 * merger / split
	 */
	
	if (Glob->params.debug >= DEBUG_EXTRA) {
	  fprintf(stderr, "STARTING_SEARCH ....\n");
	}

	process_storms1_entry(storms1, storms2, nstorms1, nstorms2,
			      match->storm_num, jstorm);
      } /* kstorm */
      
      if (Glob->params.debug >= DEBUG_EXTRA) {
	fprintf(stderr, "#### COMMON COMPLEX NUMS - Storm2 array %ld ####\n",
		(long) jstorm);
	for (i = 0; i < N_complex_nums; i++) {
	  fprintf(stderr, "%ld/%ld",
		  (long) Storm1_nums[i], (long) Complex_nums[i]);
	  if (i == N_complex_nums - 1) {
	    fprintf(stderr, "\n");
	  } else {
	    fprintf(stderr, " ");
	  }
	} /* i */
      }
      
      /*
       * find min complex num
       */

      min_complex = 999999999;
      for (i = 0; i < N_complex_nums; i++) {
	min_complex = MIN(min_complex, Complex_nums[i]);
      }

      /*
       * consolidate the tracks, using the min complex number
       */

      for (i = 0; i < N_complex_nums; i++) {
	if (Complex_nums[i] != min_complex) {
	  consolidate(t_handle,
		      storms1, storms2,
		      nstorms1, nstorms2,
		      min_complex,
		      Complex_nums[i],
		      track_utime);
	  
	}
      } /* i */
      
    } /*  if (!storm->checked) */

  } /* jstorm */
  
 return;

}