示例#1
0
void quaterN::transition0(const quater& aa, const quater& bb, int duration)
{
	quater a(aa);
	quater b(bb);
	quater qid;
	qid.identity();
	a.align(qid);
	b.align(qid);
	// kovar paper (prefer identity quaternion (more safe))
	setSize(duration);

	float totalTime=duration+1;
	float currTime;
	quater c, d, qi;
	qi.identity();
	for(int i=0; i<duration; i++)
	{
		currTime=(float)(i+1)/totalTime;
		float t=-2.f*CUBIC(currTime)+3.f*SQR(currTime);
		c.slerp(a, qi, t);
		d.slerp(qi, b, t);
		row(i).slerp(c, d, currTime);
	}
}
示例#2
0
static void validate_regex( const music_details& desc, int bells )
{
  static string allowed;
  if ( allowed.empty() ) {
    allowed.append( row(bells).print() );
    allowed.append("*?[]");
  }

  string tok( desc.get() );

  if ( tok.find_first_not_of( allowed ) != string::npos )
    throw runtime_error( make_string() << "Illegal regular expression: " 
			 << tok );

  bool inbrack(false);
  for ( string::const_iterator i(tok.begin()), e(tok.end()); i!=e; ++i ) 
    switch (*i) {
    case '[':
      if ( inbrack ) 
	throw runtime_error( "Unexpected '[' in regular expressions" );
      inbrack = true;
      break;
    case ']':
      if ( !inbrack )
	throw runtime_error( "Unexpected ']' in regular expressions" );
      inbrack = false;
      break;
    case '*': case '?':
      if ( inbrack )
	throw runtime_error( "Cannot use '*' or '?' in a [] block "
			     "of a regular expression" );
      break;
    }

  // TODO: Check for multiple occurances of the same bell
}
示例#3
0
void SubsetSingleBench::onDraw(int n, SkCanvas* canvas) {
    // When the color type is kIndex8, we will need to store the color table.  If it is
    // used, it will be initialized by the codec.
    int colorCount;
    SkPMColor colors[256];
    if (fUseCodec) {
        for (int count = 0; count < n; count++) {
            SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(fStream->duplicate()));
            const SkImageInfo info = codec->getInfo().makeColorType(fColorType);
            SkAutoTDeleteArray<uint8_t> row(new uint8_t[info.minRowBytes()]);
            codec->startScanlineDecode(info, nullptr, colors, &colorCount);

            SkBitmap bitmap;
            SkImageInfo subsetInfo = info.makeWH(fSubsetWidth, fSubsetHeight);
            alloc_pixels(&bitmap, subsetInfo, colors, colorCount);

            codec->skipScanlines(fOffsetTop);
            uint32_t bpp = info.bytesPerPixel();
            for (uint32_t y = 0; y < fSubsetHeight; y++) {
                codec->getScanlines(row.get(), 1, 0);
                memcpy(bitmap.getAddr(0, y), row.get() + fOffsetLeft * bpp,
                        fSubsetWidth * bpp);
            }
        }
    } else {
        for (int count = 0; count < n; count++) {
            SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(fStream));
            int width, height;
            decoder->buildTileIndex(fStream->duplicate(), &width, &height);
            SkBitmap bitmap;
            SkIRect rect = SkIRect::MakeXYWH(fOffsetLeft, fOffsetTop, fSubsetWidth,
                    fSubsetHeight);
            decoder->decodeSubset(&bitmap, rect, fColorType);
        }
    }
}
示例#4
0
void EventView::mouseDoubleClickEvent(QMouseEvent *event)
{
	QListWidgetItem *selectedItem = itemAt(event->pos());
	if (selectedItem != NULL)
	{
		int selectedRow = row(selectedItem);
		if (!item(selectedRow)->text().contains(QRegExp("^\\s*::")))
		{
			BaseEvent *eventToAdd = BaseEvent::browseEvents(currentEvent->getBaseType(), callerID, callerType);
			if (eventToAdd != NULL)
			{
				int row = currentRow();
				int eventsID = childEventIDAtRow(row);
				int parentID = eventsParentIDAtRow(row);
				int childTypeID = childEventTypeIDAtRow(row);
				eventList[parentID]->addChildEvent(eventToAdd, eventsID, childTypeID);
				updateView();
				eventList.clear();
				eventList = currentEvent->getEventPointers();
				setCurrentRow(row);
			}
		}
	}
}
void SolverFormulacaoPadrao::UpdateConsUpperBound(double upper) {
  // constraint
  ConstraintFormulacaoPadrao cons;
  // variable
  VariableFormulacaoPadrao var;

  // creates the constraint
  cons.reset();
  cons.set_type(ConstraintFormulacaoPadrao::C_UPPER_BOUND);
  ConstraintFormulacaoPadraoHash::iterator it = cHash_.find(cons);

  if (it == cHash_.end()) {
    cHash_[cons] = lp_->getNumRows();
    int nnz = problem_data_->num_tasks();
    OPT_ROW row(nnz, OPT_ROW::LESS, upper, (char*) cons.ToString().c_str());

    // adds each variable
    for (int i = 0; i < problem_data_->num_machines(); ++i) {
      for (int j = 0; j < problem_data_->num_tasks(); ++j) {
        var.reset();
        var.set_type(VariableFormulacaoPadrao::X_ij);
        var.set_machine(i);
        var.set_task(j);
        VariableFormulacaoPadraoHash::iterator vit = vHash_.find(var);

        //CHECK_NE(vit, vHash_.end());

        double cost = problem_data_->cost(i, j);
        row.insert(vit->second, cost);
      }
    }
    lp_->addRow(row);
  } else {
    lp_->chgRHS(it->second, upper);
  }
}
int main (int argc, char **argv){
  int number;
  int height;
  int position = 2;
  int space = 0;
  int space2 =0;
  int space3 = 0;
  /*checking if there are arguments or if the argument is negative*/
  if (argc == 1 || argv[1][0] == '-'){
    return 0;
  }
  number = char_to_int(argv);
  /*Iterating though the first part of the cross*/
  for(height = 0; height < number/2; height ++){
    space = spaces(space);
    position = row(number, position);
    space2 = spaces2(space2);
  }
  /*Printing an x in the middle if the number is odd*/
  if (number % 2 != 0){
    space = spaces(space);
    write(1, "X", 1);
    space2 = spaces2(space2);
    space2 --;
  }
  space3 = space2;
  /*This is done so that the spaces before the symbles start form the middle of the second part of the cross*/
  space = number/2 - 1;
  position -=1;
  for(height = 0; height < number/2; height ++){
  space = spaces(space) - 2;
  position =row2(number, position);
  space3 = spaces3(space3);
  }
  return 0;
}
示例#7
0
void test_math_matrix_mult_TCRRMV(void)
{
	T d1[M*N];

	for(unsigned i=0; i<(M*N); ++i)
	{
		d1[i] = T(std::rand()%10000)/2;
	}

	T d2[N*K];

	for(unsigned i=0; i<(N*K); ++i)
	{
		d2[i] = T(std::rand()%10000)/2;
	}

	auto m1 = eagine::math::matrix<T, N, M, RM1, V>::from(d1, M*N);
	auto m2 = eagine::math::matrix<T, K, N, RM2, V>::from(d2, N*K);

	eagine::math::matrix<T, K, M, RM1, V> m = multiply(m1, m2);
	(void)m;

	for(unsigned i=0; i<M; ++i)
	for(unsigned j=0; j<K; ++j)
	{
		T e = T(0);

		for(unsigned k=0; k<N; ++k)
		{
			e += row(m1, i)[k]*column(m2, j)[k];
		}

		BOOST_CHECK_EQUAL(get_cm(m, j, i), e);
		BOOST_CHECK_EQUAL(get_rm(m, i, j), e);
	}
}
示例#8
0
void CUI_LoadMsg::draw(Drawable *S) {
    int i;

    char *str[] = { "Please wait, loading... |",
                    "Please wait, loading... /",
                    "Please wait, loading... -",
                    "Please wait, loading... \\"
    };

    if (S->lock()==0) {
        S->fillRect(col(15),row(20),640-col(15)-1,row(25)-1,COLORS.Background);
        printline(col(15),row(24),148,50,COLORS.Lowlight,S);
        for (i=20;i<25;i++) {
            printchar(col(15),row(i),145,COLORS.Highlight,S);
            printchar(col(64),row(i),146,COLORS.Lowlight,S);
        }
        printline(col(15),row(20),143,50,COLORS.Highlight,S);
        print(col(textcenter(str[strselect],40)),row(22),str[strselect],COLORS.Text,S);
        S->unlock();
        need_refresh = 0;
        updated++;
    }
}
示例#9
0
PyObject *getEuclideanDistMat(python::object descripMat) {
    // Bit of a pain involved here, we accept three types of PyObjects here
    // 1. A Numeric Array
    //     - first find what 'type' of entry we have (float, double and int is all we recognize for now)
    //     - then point to contiguous piece of memory from the array that contains the data with a type*
    //     - then make a new type** pointer so that double index into this contiguous memory will work
    //       and then pass it along to the distance calculator
    // 2. A list of Numeric Vector (or 1D arrays)
    //     - in this case wrap descripMat with a PySequenceHolder<type*> where type is the
    //       type of entry in vector (accepted types are int, double and float
    //     - Then pass the PySequenceHolder to the metrci calculator
    // 3. A list (or tuple) of lists (or tuple)
    //     - In this case other than wrapping descripMat with a PySequenceHolder
    //       each of the indivual list in there are also wrapped by a PySequenceHolder
    //     - so the distance calculator is passed in a "PySequenceHolder<PySequenceHolder<double>>"
    //     - FIX: not that we always convert entry values to double here, even if we passed
    //       in a list of list of ints (or floats). Given that lists can be heterogeneous, I do not
    //       know how to ask a list what type of entries if contains.
    //
    //  OK my brain is going to explode now

    // first deal with situation where we have an Numeric Array
    PyObject *descMatObj = descripMat.ptr();
    PyArrayObject *distRes;
    if (PyArray_Check(descMatObj)) {
        // get the dimensions of the array
        int nrows = ((PyArrayObject *)descMatObj)->dimensions[0];
        int ncols = ((PyArrayObject *)descMatObj)->dimensions[1];
        int i;
        CHECK_INVARIANT((nrows > 0) && (ncols > 0), "");

        npy_intp dMatLen = nrows*(nrows-1)/2;

        // now that we have the dimensions declare the distance matrix which is always a
        // 1D double array
        distRes = (PyArrayObject *)PyArray_SimpleNew(1, &dMatLen, NPY_DOUBLE);

        // grab a pointer to the data in the array so that we can directly put values in there
        // and avoid copying :
        double *dMat = (double *)distRes->data;

        PyArrayObject *copy;
        copy = (PyArrayObject *)PyArray_ContiguousFromObject(descMatObj,
                ((PyArrayObject *)descMatObj)->descr->type_num,
                2,2);
        // if we have double array
        if (((PyArrayObject *)descMatObj)->descr->type_num == NPY_DOUBLE) {
            double *desc = (double *)copy->data;

            // REVIEW: create an adaptor object to hold a double * and support
            //  operator[]() so that we don't have to do this stuff:

            // here is the 2D array trick this so that when the distance calaculator
            // asks for desc2D[i] we basically get the ith row as double*
            double **desc2D = new double*[nrows];
            for (i = 0; i < nrows; i++) {
                desc2D[i] = desc;
                desc += ncols;
            }
            MetricMatrixCalc<double**, double*> mmCalc;
            mmCalc.setMetricFunc(&EuclideanDistanceMetric<double *, double *>);
            mmCalc.calcMetricMatrix(desc2D, nrows, ncols, dMat);

            delete [] desc2D;
            // we got the distance matrix we are happy so return
            return PyArray_Return(distRes);
        }

        // if we have a float array
        else if (((PyArrayObject *)descMatObj)->descr->type_num == NPY_FLOAT) {
            float* desc = (float *)copy->data;
            float **desc2D = new float*[nrows];
            for (i = 0; i < nrows; i++) {
                desc2D[i] = desc;
                desc += ncols;
            }
            MetricMatrixCalc<float**, float*> mmCalc;
            mmCalc.setMetricFunc(&EuclideanDistanceMetric<float *, float*>);
            mmCalc.calcMetricMatrix(desc2D, nrows, ncols, dMat);
            delete [] desc2D;
            return PyArray_Return(distRes);
        }

        // if we have an interger array
        else if (((PyArrayObject *)descMatObj)->descr->type_num == NPY_INT) {
            int *desc = (int *)copy->data;
            int **desc2D = new int*[nrows];
            for (i = 0; i < nrows; i++) {
                desc2D[i] = desc;
                desc += ncols;
            }
            MetricMatrixCalc<int**, int*> mmCalc;
            mmCalc.setMetricFunc(&EuclideanDistanceMetric<int *, int*>);
            mmCalc.calcMetricMatrix(desc2D, nrows, ncols, dMat);
            delete [] desc2D;
            return PyArray_Return(distRes);
        }
        else {
            // unreconiged type for the matrix, throw up
            throw_value_error("The array has to be of type int, float, or double for GetEuclideanDistMat");
        }
    } // done with an array input
    else {
        // REVIEW: removed a ton of code here

        // we have probably have a list or a tuple

        unsigned int ncols = 0;
        unsigned int nrows = python::extract<unsigned int>(descripMat.attr("__len__")());
        CHECK_INVARIANT(nrows > 0, "Empty list passed in");

        npy_intp dMatLen = nrows*(nrows-1)/2;
        distRes = (PyArrayObject *)PyArray_SimpleNew(1, &dMatLen, NPY_DOUBLE);
        double *dMat = (double *)distRes->data;

        // assume that we a have a list of list of values (that can be extracted to double)
        std::vector<PySequenceHolder<double> > dData;
        dData.reserve(nrows);
        for (unsigned int i = 0; i < nrows; i++) {
            //PySequenceHolder<double> row(seq[i]);
            PySequenceHolder<double> row(descripMat[i]);
            if(i==0) {
                ncols = row.size();
            } else if( row.size() != ncols ) {
                throw_value_error("All subsequences must be the same length");
            }
            dData.push_back(row);
        }

        MetricMatrixCalc< std::vector<PySequenceHolder<double> >, PySequenceHolder<double> > mmCalc;
        mmCalc.setMetricFunc(&EuclideanDistanceMetric< PySequenceHolder<double>, PySequenceHolder<double> >);
        mmCalc.calcMetricMatrix(dData, nrows, ncols, dMat);
    }
    return PyArray_Return(distRes);
}
void InfoShape::draw(const DrawBuf &buf) const
 {
  if( !pane ) return;

  Smooth::DrawArt art(buf);

  VColor text=enable?+cfg.text:+cfg.inactive;

  Point space=+cfg.space;

  // decor

  {
   MPane p(pane);

   MCoord width=+cfg.width;
   MCoord dx=Fraction(space.x)-width;
   MCoord dy=Fraction(space.y)-width;

   if( focus )
     {
      FigureBox fig(p.shrink(Fraction(space.x)/2,Fraction(space.y)/2));

      fig.loop(art,width,+cfg.focus);
     }

   if( xoff>0 )
     {
      FigureLeftMark fig(p,dx);

      fig.solid(art,text);
     }

   if( xoff<xoffMax )
     {
      FigureRightMark fig(p,dx);

      fig.solid(art,text);
     }

   if( yoff>0 )
     {
      FigureUpMark fig(p,dy);

      fig.solid(art,text);
     }

   if( yoff<yoffMax )
     {
      FigureDownMark fig(p,dy);

      fig.solid(art,text);
     }
  }

  // text

  {
   Pane inner=pane.shrink(space);

   if( !inner ) return;

   ulen count=info->getLineCount();
   ulen index=yoff;

   Font font=cfg.font.get();

   FontSize fs=font->getSize();

   DrawBuf tbuf=buf.cutRebase(inner);

   Pane row(-xoff,0,IntAdd(xoff,inner.dx),fs.dy);

   for(; index<count && row.y+row.dy<=inner.dy ;index++,row.y+=row.dy)
     {
      font->text(tbuf,row,TextPlace(AlignX_Left,AlignY_Top),info->getLine(index),text);
     }
  }
 }
示例#11
0
std::pair<double,double> benchmark_spmv_ccsr(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    // Construct matrix for 3D Poisson problem in cubic domain.
    const uint n = 128;
    const uint N = n * n * n;
    const uint M = 1024;

    double time_elapsed;

    const real h2i = (n - 1) * (n - 1);

    std::vector<size_t> idx;
    std::vector<size_t> row(3);
    std::vector<int>    col(8);
    std::vector<real>   val(8);

    std::vector<real>   X(n * n * n, static_cast<real>(1e-2));
    std::vector<real>   Y(n * n * n, 0);

    idx.reserve(n * n * n);

    row[0] = 0;
    row[1] = 1;
    row[2] = 8;

    col[0] = 0;
    val[0] = 1;

    col[1] = -static_cast<int>(n * n);
    col[2] = -static_cast<int>(n);
    col[3] =    -1;
    col[4] =     0;
    col[5] =     1;
    col[6] =     n;
    col[7] =  (n * n);

    val[1] = -h2i;
    val[2] = -h2i;
    val[3] = -h2i;
    val[4] =  h2i * 6;
    val[5] = -h2i;
    val[6] = -h2i;
    val[7] = -h2i;

    for(size_t k = 0; k < n; k++) {
        for(size_t j = 0; j < n; j++) {
            for(size_t i = 0; i < n; i++) {
                if (
                        i == 0 || i == (n - 1) ||
                        j == 0 || j == (n - 1) ||
                        k == 0 || k == (n - 1)
                   )
                {
                    idx.push_back(0);
                } else {
                    idx.push_back(1);
                }
            }
        }
    }

    size_t nnz = 6 * (n - 2) * (n - 2) * (n - 2) + n * n * n;

    // Transfer data to compute devices.
    vex::SpMatCCSR<real,int> A(ctx.queue(0), n * n * n, 2,
            idx.data(), row.data(), col.data(), val.data());

    std::vector<vex::command_queue> q1(1, ctx.queue(0));
    vex::vector<real> x(q1, X);
    vex::vector<real> y(q1, Y);

    // Get timings.
    y += A * x;
    y = 0;

    prof.tic_cpu("OpenCL");
    for(size_t i = 0; i < M; i++)
        y += A * x;
    ctx.finish();
    time_elapsed = prof.toc("OpenCL");

    double gflops = (2.0 * nnz + N) * M / time_elapsed / 1e9;
    double bwidth = M * (nnz * (2 * sizeof(real) + sizeof(int)) + 4 * N * sizeof(real)) / time_elapsed / 1e9;

    std::cout
        << "SpMV (CCSR) (" << vex::type_name<real>() << ")\n"
        << "  OpenCL"
        << "\n    GFLOPS:    " << gflops
        << "\n    Bandwidth: " << bwidth
        << std::endl;

    if (options.bm_cpu) {
        prof.tic_cpu("C++");
        for(size_t k = 0; k < M; k++)
            for(size_t i = 0; i < N; i++) {
                real s = 0;
                for(size_t j = row[idx[i]]; j < row[idx[i] + 1]; j++)
                    s += val[j] * X[i + col[j]];
                Y[i] += s;
            }
        time_elapsed = prof.toc("C++");

        {
            double gflops = (2.0 * nnz + N) * M / time_elapsed / 1e9;
            double bwidth = M * (nnz * (2 * sizeof(real) + sizeof(int)) + 4 * N * sizeof(real)) / time_elapsed / 1e9;

            std::cout
                << "  C++"
                << "\n    GFLOPS:    " << gflops
                << "\n    Bandwidth: " << bwidth
                << std::endl;
        }

        copy(Y, x);

        y -= x;

        vex::Reductor<real, vex::SUM> sum(q1);

        std::cout << "  res = " << sum(y * y) << std::endl << std::endl;
    }

    return std::make_pair(gflops, bwidth);
}
示例#12
0
 Vector4T<T>&       operator[](int i)      { return row(i); }
OP_STATUS ExtensionsManagerListViewItem::ConstructItemWidget(QuickWidget** widget)
{
	*widget = NULL;

	// name_col

	OpAutoPtr<QuickStackLayout> name_col(
			OP_NEW(QuickStackLayout, (QuickStackLayout::VERTICAL)));
	RETURN_OOM_IF_NULL(name_col.get());

	name_col->SetPreferredWidth(WidgetSizes::Fill);
	name_col->SetMinimumWidth(EXTENSION_NAME_MINIMUM_WIDTH);
	m_extension_name = ConstructName();
	RETURN_OOM_IF_NULL(m_extension_name);
	RETURN_IF_ERROR(name_col->InsertWidget(m_extension_name));
	m_author_version = ConstructAuthorAndVersion();
	RETURN_OOM_IF_NULL(m_author_version);
	RETURN_IF_ERROR(name_col->InsertWidget(m_author_version));

	// name_and_buttons_row

	OpAutoPtr<QuickStackLayout> name_and_buttons_row(
			OP_NEW(QuickStackLayout, (QuickStackLayout::HORIZONTAL)));
	RETURN_OOM_IF_NULL(name_and_buttons_row.get());

	RETURN_IF_ERROR(name_and_buttons_row->InsertWidget(name_col.release()));
	QuickStackLayout* control_buttons = ConstructControlButtons();
	RETURN_OOM_IF_NULL(control_buttons);
	RETURN_IF_ERROR(name_and_buttons_row->InsertWidget(control_buttons));

	// main_col

	OpAutoPtr<QuickStackLayout> main_col(
			OP_NEW(QuickStackLayout, (QuickStackLayout::VERTICAL)));
	RETURN_OOM_IF_NULL(main_col.get());

	RETURN_IF_ERROR(main_col->InsertWidget(name_and_buttons_row.release()));
	RETURN_IF_ERROR(main_col->InsertEmptyWidget(0, TEXT_SPACING, 0, TEXT_SPACING));
	m_description = ConstructDescription();
	RETURN_OOM_IF_NULL(m_description);
	RETURN_IF_ERROR(main_col->InsertWidget(m_description));
	QuickStackLayout* debug_buttons = ConstructDebugButtons();
	if (debug_buttons)
	{
		RETURN_IF_ERROR(main_col->InsertWidget(debug_buttons));
	}

	// row_content

	OpAutoPtr<QuickStackLayout> row_content(
			OP_NEW(QuickStackLayout, (QuickStackLayout::HORIZONTAL)));
	RETURN_OOM_IF_NULL(row_content.get());

	RETURN_IF_ERROR(
			row_content->InsertEmptyWidget(EXTENSION_ICON_PADDING, 0, EXTENSION_ICON_PADDING, 0));
	m_icon = ConstructExtensionIcon();
	RETURN_OOM_IF_NULL(m_icon);
	RETURN_IF_ERROR(row_content->InsertWidget(m_icon));
	RETURN_IF_ERROR(
			row_content->InsertEmptyWidget(EXTENSION_ICON_PADDING, 0, EXTENSION_ICON_PADDING, 0));
	RETURN_IF_ERROR(row_content->InsertWidget(main_col.release()));
	if (debug_buttons)
	{
		RETURN_IF_ERROR(row_content->InsertEmptyWidget(2, 0, 2, 0));
	}

	// row

	OpAutoPtr<QuickStackLayout> row(
			OP_NEW(QuickStackLayout, (QuickStackLayout::VERTICAL)));
	RETURN_OOM_IF_NULL(row.get());

	RETURN_IF_ERROR(row->InsertEmptyWidget(0, ROW_ITEM_TOP_PADDING, 0, 
			ROW_ITEM_TOP_PADDING));
	RETURN_IF_ERROR(row->InsertWidget(row_content.release()));
	RETURN_IF_ERROR(row->InsertEmptyWidget(0, ROW_ITEM_BOTTOM_PADDING, 0, 
			ROW_ITEM_BOTTOM_PADDING));

	QuickSkinElement *quick_skin_element =
			QuickSkinWrap(row.release(), "Extensions Panel List Item Skin");
	RETURN_OOM_IF_NULL(quick_skin_element);

	quick_skin_element->GetOpWidget()->SetAlwaysHoverable(TRUE);

	*widget = quick_skin_element;

	UpdateControlButtonsState();
	SetEnabled(!GetModelItem().IsDisabled());

	return OpStatus::OK;
}
示例#14
0
shared_ptr<HtmlTableRow> HtmlTable::addRow()
{
	shared_ptr<HtmlTableRow> row(OS_NEW HtmlTableRow());
	getControls()->add(row);
	return row;
}
const float4x4 float4x4::operator * (const float4x4& b) const
{
#if 1
  // a textbook implementation...
  float4x4 c;
  const float4x4 &a = *this;

  for (int i = 1; i <= 4; ++i)
  {
      for (int k = 1; k <= 4; ++k)
      {
        c(i, k) = a(i, 1) * b(1, k) 
                + a(i, 2) * b(2, k) 
                + a(i, 3) * b(3, k) 
                + a(i, 4) * b(4, k);
      }
  }

  return c;
#else
  // assuredly slow, since row() does a lot of logic...
  return make_matrix(dot(row(0), m.c1), dot(row(0), m.c2), dot(row(0), m.c3), dot(row(0), m.c4),  
		  dot(row(1), m.c1), dot(row(1), m.c2), dot(row(1), m.c3), dot(row(1), m.c4), 
		  dot(row(2), m.c1), dot(row(2), m.c2), dot(row(2), m.c3), dot(row(2), m.c4), 
		  dot(row(3), m.c1), dot(row(3), m.c2), dot(row(3), m.c3), dot(row(3), m.c4));
#endif
}
示例#16
0
void SaveBitmapToFile( const char * fname, LVGrayDrawBuf * bmp )
{
    if (!bmp)
        return;
    LVStreamRef stream = LVOpenFileStream(fname, LVOM_WRITE);
    if (!stream)
        return;
    int rowsize = ((bmp->GetWidth()+1)/2);
    int img_size = rowsize * bmp->GetHeight();
    int padding = rowsize - rowsize;
    BITMAPFILEHEADER fh;
    struct {
        BITMAPINFOHEADER hdr;
        RGBQUAD colors[16];
    } bmi;
    memset(&fh, 0, sizeof(fh));
    memset(&bmi, 0, sizeof(bmi));
    fh.bfType = 0x4D42;
    fh.bfSize = sizeof(fh) + sizeof(bmi) + img_size;
    fh.bfOffBits = sizeof(fh) + sizeof(bmi);
    bmi.hdr.biSize = sizeof(bmi.hdr);
    bmi.hdr.biWidth = bmp->GetWidth();
    bmi.hdr.biHeight = bmp->GetHeight();
    bmi.hdr.biPlanes = 1;
    bmi.hdr.biBitCount = 4;
    bmi.hdr.biCompression = 0;
    bmi.hdr.biSizeImage = img_size;
    bmi.hdr.biXPelsPerMeter = 0xEC4;
    bmi.hdr.biYPelsPerMeter = 0xEC4;
    bmi.hdr.biClrUsed = 16;
    bmi.hdr.biClrImportant = 16;
    static lUInt8 gray[8] = { 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xAA, 0x55, 0x00 };
    lUInt8 * pal = bmp->GetBitsPerPixel()==1?gray+0:gray+4;
    for (int i=0; i<4; i++)
    {
        bmi.colors[i].rgbBlue = pal[i];
        bmi.colors[i].rgbGreen = pal[i];
        bmi.colors[i].rgbRed = pal[i];
    }
    stream->Write( &fh, sizeof(fh), NULL );
    stream->Write( &bmi, sizeof(bmi), NULL );
    static const lUInt8 dummy[3] = {0,0,0};
    for (int y=0; y<bmp->GetHeight(); y++)
    {
        LVArray<lUInt8> row( (bmp->GetWidth()+1)/2, 0 );
        for ( int x=0; x<bmp->GetWidth(); x++)
        {
            int cl = bmp->GetPixel(x, bmp->GetHeight()-1-y);
            //int cl = (src[x/8] >> ((1-(x&3))*2)) & 3;
            row[x/2] = row[x/2] | (cl << ((x&1)?0:4));
        }
        row[0] = 0x11;
        row[1] = 0x11;
        row[2] = 0x22;
        row[3] = 0x22;
        row[4] = 0x33;
        row[5] = 0x33;
        *stream << row;
        if (padding)
            stream->Write( dummy, padding, NULL );
    }
}
示例#17
0
        void Fibre::Tractlet::Tensor::add_section_hessian(
                const Tractlet& tractlet, const Tractlet::Section& section,
                const Strand::BasicSection& gradient, const Strand::BasicSection::Tensor& hessian) {
            
            Fibre::Tractlet d2_intensity = get_template();
            
            Strand pos_gradient = Strand::outer_product(section.position_coeffs,
                    gradient.position() / section.intensity());
            
            if (has_var_acs())
                d2_intensity.set_acs(0.0);
            
//      d2_intensity.set_base_width(0.0);
            
//Add position gradient.
            d2_intensity[0] += pos_gradient;
            d2_intensity[1] += pos_gradient * section.ax1_fraction;
            d2_intensity[2] += pos_gradient * section.ax2_fraction;
            
            //Add tangent gradient.
            
            Strand tang_gradient = Strand::outer_product(section.tangent_coeffs,
                    gradient.tangent() * (section.length_fraction / section.intensity()));
            
            d2_intensity[0] += tang_gradient;
            d2_intensity[1] += tang_gradient * section.ax1_fraction;
            d2_intensity[2] += tang_gradient * section.ax2_fraction;
            
            Fibre::Tractlet acs_gradient = d2_intensity * section.intensity();
            
            if (true) {    //Needs some serious rewriting.
            
                throw Exception(
                        "tied_width hessian needs to be adjusted after accounting for tractlet sheer.");
                
                double norm1 = tractlet[1][0].norm();
                double norm2 = tractlet[2][0].norm();
                
                Coord d_intensity_d1 = tractlet.acs()
                        * ((norm2 / norm1) * tractlet(1, 0) - tractlet(2, 0));
                Coord d_intensity_d2 = tractlet.acs()
                        * ((norm1 / norm2) * tractlet(2, 0) - tractlet(1, 0));
                
                for (size_t dim_i1 = 0; dim_i1 < 3; dim_i1++) {
                    
                    operator()(1, 0, dim_i1, 2, 0, dim_i1) -= gradient.intensity() * tractlet.acs();
                    operator()(2, 0, dim_i1, 1, 0, dim_i1) -= gradient.intensity() * tractlet.acs();
                    
                    operator()(1, 0, dim_i1, 1, 0, dim_i1) += gradient.intensity() * tractlet.acs()
                                                              * norm2
                                                              / norm1;
                    operator()(2, 0, dim_i1, 2, 0, dim_i1) += gradient.intensity() * tractlet.acs()
                                                              * norm1
                                                              / norm2;
                    
                    for (size_t dim_i2 = 0; dim_i2 < 3; dim_i2++) {
                        
                        operator()(1, 0, dim_i1, 1, 0, dim_i2) -= tractlet.acs()
                                * gradient.intensity() * tractlet[1][0][dim_i1]
                                * tractlet[1][0][dim_i2] * (norm2 / MR::Math::pow3(norm1));
                        operator()(2, 0, dim_i1, 2, 0, dim_i2) -= tractlet.acs()
                                * gradient.intensity() * tractlet[2][0][dim_i1]
                                * tractlet[2][0][dim_i2] * (norm1 / MR::Math::pow3(norm2));
                        
                        operator()(1, 0, dim_i1, 2, 0, dim_i2) += tractlet.acs()
                                * gradient.intensity() * tractlet[2][0][dim_i2]
                                * tractlet[1][0][dim_i1]
                                                                  / (norm1 * norm2);
                        operator()(2, 0, dim_i1, 1, 0, dim_i2) += tractlet.acs()
                                * gradient.intensity() * tractlet[1][0][dim_i2]
                                * tractlet[2][0][dim_i1]
                                                                  / (norm2 * norm1);
                        
                        for (size_t ax_i = 0; ax_i < 3; ++ax_i)
                            for (size_t degree_i = 0; degree_i < tractlet.degree(); ++degree_i) {
                                
                                operator()(ax_i, degree_i, dim_i1, 1, 0, dim_i2) += tractlet.acs()
                                        * d2_intensity(ax_i, degree_i)[dim_i1]
                                        * d_intensity_d1[dim_i2];
                                operator()(ax_i, degree_i, dim_i1, 2, 0, dim_i2) += tractlet.acs()
                                        * d2_intensity(ax_i, degree_i)[dim_i1]
                                        * d_intensity_d2[dim_i2];
                                
                                operator()(1, 0, dim_i1, ax_i, degree_i, dim_i2) += tractlet.acs()
                                        * d2_intensity(ax_i, degree_i)[dim_i2]
                                        * d_intensity_d1[dim_i1];
                                operator()(2, 0, dim_i1, ax_i, degree_i, dim_i2) += tractlet.acs()
                                        * d2_intensity(ax_i, degree_i)[dim_i2]
                                        * d_intensity_d2[dim_i1];
                                
                            }
                        
                    }
                    
                }
                
                if (has_var_acs()) {
                    acs_gradient(1, 0) += gradient.intensity() * d_intensity_d1;
                    acs_gradient(2, 0) += gradient.intensity() * d_intensity_d2;
                }
                
            }
            
            if (has_var_acs())
                acs() += acs_gradient;
            
            for (size_t degree_i1 = 0; degree_i1 < degree(); degree_i1++)
                for (size_t dim_i1 = 0; dim_i1 < 3; dim_i1++) {
                    
                    Fibre::Tractlet ax0 = row(0, degree_i1, dim_i1);
                    Fibre::Tractlet ax1 = row(1, degree_i1, dim_i1);
                    Fibre::Tractlet ax2 = row(2, degree_i1, dim_i1);
                    
                    if (has_var_acs()) {
                        ax0.alpha() += acs_gradient.operator()(0, degree_i1)[dim_i1];
                        ax1.alpha() += acs_gradient.operator()(1, degree_i1)[dim_i1];
                        ax2.alpha() += acs_gradient.operator()(2, degree_i1)[dim_i1];
                    }
                    
                    for (size_t degree_i2 = 0; degree_i2 < degree(); degree_i2++)
                        for (size_t dim_i2 = 0; dim_i2 < 3; dim_i2++) {
                            
                            double ax0_ax0 =
                                    section.position_coeffs[degree_i1] * section.position_coeffs[degree_i2]
                                    * hessian.position(dim_i1).position(dim_i2)
                                    + section.position_coeffs[degree_i1] * section.tangent_coeffs[degree_i2]
                                      * hessian.position(dim_i1).tangent(dim_i2)
                                      * section.length_fraction
                                    + section.tangent_coeffs[degree_i1] * section.position_coeffs[degree_i2]
                                      * hessian.tangent(dim_i1).position(dim_i2)
                                      * section.length_fraction
                                    + section.tangent_coeffs[degree_i1] * section.tangent_coeffs[degree_i2]
                                      * hessian.tangent(dim_i1).tangent(dim_i2)
                                      * MR::Math::pow2(section.length_fraction);
                            
                            ax0[0][degree_i2][dim_i2] += ax0_ax0;
                            ax0[1][degree_i2][dim_i2] += ax0_ax0 * section.ax1_fraction;
                            ax1[0][degree_i2][dim_i2] += ax0_ax0 * section.ax1_fraction;
                            ax0[2][degree_i2][dim_i2] += ax0_ax0 * section.ax2_fraction;
                            ax2[0][degree_i2][dim_i2] += ax0_ax0 * section.ax2_fraction;
                            
                            ax1[1][degree_i2][dim_i2] += ax0_ax0
                                    * MR::Math::pow2(section.ax1_fraction);
                            ax1[2][degree_i2][dim_i2] += ax0_ax0 * section.ax1_fraction
                                                         * section.ax2_fraction;
                            ax2[1][degree_i2][dim_i2] += ax0_ax0 * section.ax1_fraction
                                                         * section.ax2_fraction;
                            
                            ax2[2][degree_i2][dim_i2] += ax0_ax0
                                    * MR::Math::pow2(section.ax2_fraction);
                            
                        }
                    
                }
            
        }
示例#18
0
void EffectRack::menuRequested(QListWidgetItem* it)/*{{{*/
{
    if (it == 0 || track == 0)
        return;
    RackSlot* curitem = (RackSlot*) it;

    Pipeline* epipe = track->efxPipe();

    int idx = row(curitem);
    QString name;
    bool mute = false;
    bool nativeGui = false;
    Pipeline* pipe = track->efxPipe();
    if (pipe)
    {
        name = pipe->name(idx);
        mute = (pipe->isActive(idx) == false);
        nativeGui = pipe->hasNativeGui(idx);
    }

    //enum { NEW, CHANGE, UP, DOWN, REMOVE, BYPASS, SHOW, SAVE };

    enum
    {
        NEW, CHANGE, UP, DOWN, REMOVE, BYPASS, SHOW, SHOW_NATIVE, SAVE
    };
    QMenu* menu = new QMenu;
    QAction* newAction = menu->addAction(tr("new"));
    QAction* changeAction = menu->addAction(tr("change"));
    QAction* upAction = menu->addAction(QIcon(*upIcon), tr("move up")); //,   UP, UP);
    QAction* downAction = menu->addAction(QIcon(*downIcon), tr("move down")); //, DOWN, DOWN);
    QAction* removeAction = menu->addAction(tr("remove")); //,    REMOVE, REMOVE);
    QAction* bypassAction = menu->addAction(tr("bypass")); //,    BYPASS, BYPASS);
    QAction* showGuiAction = menu->addAction(tr("show gui")); //,  SHOW, SHOW);
    QAction* showNativeGuiAction = menu->addAction(tr("show native gui")); //,  SHOW_NATIVE, SHOW_NATIVE);
    QAction* saveAction = menu->addAction(tr("save preset"));

    newAction->setData(NEW);
    changeAction->setData(CHANGE);
    upAction->setData(UP);
    downAction->setData(DOWN);
    removeAction->setData(REMOVE);
    bypassAction->setData(BYPASS);
    showGuiAction->setData(SHOW);
    showNativeGuiAction->setData(SHOW_NATIVE);
    saveAction->setData(SAVE);

    bypassAction->setCheckable(true);
    showGuiAction->setCheckable(true);
    showNativeGuiAction->setCheckable(true);

    bypassAction->setChecked(mute);
    showGuiAction->setChecked(pipe->guiVisible(idx));
    showNativeGuiAction->setEnabled(nativeGui);
    if (nativeGui)
        showNativeGuiAction->setChecked(pipe->nativeGuiVisible(idx));

    if (pipe->empty(idx))
    {
        menu->removeAction(changeAction);
        menu->removeAction(saveAction);
        upAction->setEnabled(false);
        downAction->setEnabled(false);
        removeAction->setEnabled(false);
        bypassAction->setEnabled(false);
        showGuiAction->setEnabled(false);
        showNativeGuiAction->setEnabled(false);
    }
    else
    {
        menu->removeAction(newAction);
        if (idx == 0)
            upAction->setEnabled(true);
        if (idx == ((int)epipe->size() - 1))
            downAction->setEnabled(false);
    }

    QPoint pt = QCursor::pos();
    QAction* act = menu->exec(pt, 0);

    //delete menu;
    if (!act)
    {
        delete menu;
        return;
    }

    int sel = act->data().toInt();
    delete menu;

    int pdepth = epipe->size();
    switch (sel)
    {
    case NEW:
    {
        choosePlugin(it);
        break;
    }
    case CHANGE:
    {
        choosePlugin(it, true);
        break;
    }
    case REMOVE:
    {
        BasePlugin* oldPlugin = (*epipe)[idx];
        oldPlugin->setActive(false);
        oldPlugin->aboutToRemove();

        if(debugMsg)
            qCritical("Plugin to remove now and here");

        audio->msgAddPlugin(track, idx, 0);
        song->dirty = true;
        break;
    }
    case BYPASS:
    {
        bool flag = !pipe->isActive(idx);
        pipe->setActive(idx, flag);
        break;
    }
    case SHOW:
    {
        bool flag = !pipe->guiVisible(idx);
        pipe->showGui(idx, flag);
        break;
    }
    case SHOW_NATIVE:
    {
        printf("Show native GUI called\n");
        bool flag = !pipe->nativeGuiVisible(idx);
        pipe->showNativeGui(idx, flag);
        break;
    }
    case UP:
        if (idx > 0)
        {
            setCurrentItem(item(idx - 1));
            pipe->move(idx, true);
        }
        break;
    case DOWN:
        if (idx < pdepth)
        {
            setCurrentItem(item(idx + 1));
            pipe->move(idx, false);
        }
        break;
    case SAVE:
        savePreset(idx);
        break;
    }
    //Already done on songChanged
    //updateContents();
    song->update(SC_RACK);
}/*}}}*/
示例#19
0
文件: image.cpp 项目: ccrma/audicle
int
Image::write_png(char *file) const
{
   
   if (_width == 0 || _height == 0 || _data == 0) {
      fprintf(stderr,"Image::write_png: image has no data");
      return 0;
   } else if (_bpp < 1 || _bpp > 4) {
      fprintf(stderr,"Image::write_png: unsupported number of bytes/pixel (%d)",
              _bpp);
      return 0;
   }

   FILE* fp;
   if ((fp = fopen(file, "wb")) == 0) {
      fprintf(stderr,"Image::write_png: can't open file %s", file);
      return 0;
   }

   // Create and initialize the png_struct with the desired error handler
   // functions.  If you want to use the default stderr and longjump method,
   // you can supply NULL for the last three parameters.  We also check that
   // the library version is compatible with the one used at compile time,
   // in case we are using dynamically linked libraries.  REQUIRED.
   png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,0,0,0);
   if (!png_ptr) {
      fclose(fp);
      fprintf(stderr,"Image::write_png: png_create_write_struct() failed");
      return 0;
   }

   // Allocate/initialize the image information data.  REQUIRED
   png_infop info_ptr = png_create_info_struct(png_ptr);
   if (!info_ptr) {
      fclose(fp);
      png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
      fprintf(stderr,"Image::write_png: png_create_info_struct() failed");
      return 0;
   }

   // Set error handling
   if (setjmp(png_ptr->jmpbuf)) {
      // jump here from error encountered inside PNG code...
      // free all memory associated with the png_ptr and info_ptr
      fclose(fp);
      png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
      fprintf(stderr,"Image::write_png: error writing file %s", file);
      return 0;
   }

   // Set up the input control (using standard C streams)
   //
   //   see note re: C streams in read_png() above
   //
   png_init_io(png_ptr, fp);

   // set the image information:
   png_set_IHDR(png_ptr,
                info_ptr,
                _width,
                _height,
                8,                              // bit depth
                ((_bpp==4) ? PNG_COLOR_TYPE_RGB_ALPHA :
                 (_bpp==3) ? PNG_COLOR_TYPE_RGB :
                 (_bpp==2) ? PNG_COLOR_TYPE_GRAY_ALPHA :
                 PNG_COLOR_TYPE_GRAY),
                PNG_INTERLACE_NONE,
                PNG_COMPRESSION_TYPE_BASE,
                PNG_FILTER_TYPE_BASE);

   // set gamma
   double gamma = getenv("JOT_GAMMA") ? atof(getenv("JOT_GAMMA")) : 0.45;
   png_set_gAMA(png_ptr, info_ptr, gamma);
                
   // write the file header information.  REQUIRED
   png_write_info(png_ptr, info_ptr);

   // write the image data (inverted vertically):
   for (int y=_height-1; y>=0; y--)
      png_write_row(png_ptr, row(y));

   // It is REQUIRED to call this to finish writing
   png_write_end(png_ptr, info_ptr);

   // clean up after the write, and free any memory allocated
   png_destroy_write_struct(&png_ptr, (png_infopp)NULL);

   // close the file
   fclose(fp);

   return 1;
}
示例#20
0
void EffectRack::dropEvent(QDropEvent *event)/*{{{*/
{
    event->accept();
    QString text;
    QListWidgetItem *i = itemAt(event->pos());
    if (!i)
        return;
    int idx = row(i);
    //qDebug("EffectRack::dropEvent: idx: %d", idx);

    Pipeline* pipe = track->efxPipe();
    if (pipe)
    {
        //int size = pipe->size();
        /*if (idx < size)
        {
        	QWidget *sw = event->source();
        	if (sw)
        	{
        		if (strcmp(sw->metaObject()->className(), "EffectRack") == 0)
        		{
        			EffectRack *ser = (EffectRack*) sw;
        			Pipeline* spipe = ser->getTrack()->efxPipe();
        			if (!spipe)
        				return;

        			QListWidgetItem *i = ser->itemAt(ser->getDragPos());
        			int idx0 = ser->row(i);
        			if (!(*spipe)[idx0] ||
        					(idx == idx0 && (ser == this || ser->getTrack()->name() == track->name())))
        				return;
        		}
        	}
        	if (QMessageBox::question(this, tr("Replace effect"), tr("Do you really want to replace the effect %1?").arg(pipe->name(idx)),
        			QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes)
        	{
        		audio->msgAddPlugin(track, idx, 0);
        		song->update(SC_RACK);
        	}
        	else
        	{
        		return;
        	}
        }*/

        if (event->mimeData()->hasFormat("text/x-oom-plugin"))
        {
            const QMimeData *md = event->mimeData();
            QString outxml(md->data("text/x-oom-plugin"));
            //qDebug("EffectRack::dropEvent Event data:\n%s", outxml.toUtf8().constData());
            //Xml xml(event->mimeData()->data("text/x-oom-plugin").data());
            QByteArray ba = outxml.toUtf8();
            const char* data =  ba.constData();
            Xml xml(data);
            initPlugin(xml, idx);
        }
        else if (event->mimeData()->hasUrls())
        {
            // Multiple urls not supported here. Grab the first one.
            text = event->mimeData()->urls()[0].path();

            if (text.endsWith(".pre", Qt::CaseInsensitive) ||
                    text.endsWith(".pre.gz", Qt::CaseInsensitive) ||
                    text.endsWith(".pre.bz2", Qt::CaseInsensitive))
            {
                //bool popenFlag = false;
                bool popenFlag;
                FILE* fp = fileOpen(this, text, ".pre", "r", popenFlag, false, false);
                if (fp)
                {
                    Xml xml(fp);
                    initPlugin(xml, idx);

                    if (popenFlag)
                        pclose(fp);
                    else
                        fclose(fp);
                }
            }
        }
    }
}/*}}}*/
示例#21
0
void NetPrefsServerView::MessageReceived(BMessage* msg)
{
	switch (msg->what) {
	case M_SERVER_ITEM_SELECTED: {
		BRow* row(fServerList->CurrentSelection());
		if (row) {
			fEditButton->SetEnabled(true);
			fRemoveButton->SetEnabled(true);
		} else {
			fEditButton->SetEnabled(false);
			fRemoveButton->SetEnabled(false);
		}
	} break;

	case M_SERVER_ADD_ITEM: {
		BMessenger msgr(fEntryWin);
		if (msgr.IsValid())
			fEntryWin->Activate();
		else {
			fEntryWin = new ServerEntryWindow(this, new BMessage(M_SERVER_RECV_DATA), NULL, 0);
			fEntryWin->Show();
		}
	} break;

	case M_SERVER_EDIT_ITEM: {
		BMessenger msgr(fEntryWin);
		if (msgr.IsValid())
			fEntryWin->Activate();
		else {
			BRow* row(fServerList->CurrentSelection());
			if (!row) break;
			int32 count(0);
			ssize_t size(0);
			type_code type;
			fActiveNetwork->GetInfo("server", &type, &count);
			const ServerData* compData;
			for (int32 i = 0; i < count; i++) {
				fActiveNetwork->FindData("server", B_RAW_TYPE, i,
										 reinterpret_cast<const void**>(&compData), &size);
				if (!strcmp(compData->serverName, ((BStringField*)row->GetField(1))->String()))
					break;
			}
			BMessage* invoke(new BMessage(M_SERVER_RECV_DATA));
			invoke->AddBool("edit", true);
			fEntryWin = new ServerEntryWindow(this, invoke, compData, size);
			fEntryWin->Show();
		}
	} break;

	case M_SERVER_REMOVE_ITEM: {
		RemoveServer();
		fNetWin.SendMessage(M_SERVER_DATA_CHANGED);
	} break;

	case M_SERVER_RECV_DATA: {
		const ServerData* data;
		ssize_t size;
		Window()->DisableUpdates();
		msg->FindData("server", B_RAW_TYPE, reinterpret_cast<const void**>(&data), &size);
		if (msg->HasBool("edit")) RemoveServer();
		UpdateNetworkData(data);
		AddServer(data);
		Window()->EnableUpdates();
		fNetWin.SendMessage(M_SERVER_DATA_CHANGED);
	} break;

	default:
		BView::MessageReceived(msg);
		break;
	}
}
示例#22
0
void initialize_new_objects(mpi::communicator& world,
			    parameter_t const& P,  directory_structure_t const& ds,
			    geometric_info_t const& gi, object_info_t& oi,
			    vector<std::vector<std::string> > const &seq, int tt,
			    vector<CImg<unsigned char> > const& images,
			    vector<matrix<float> > const& grd,
			    vector<matrix<float> >& detected_rects)
{
    int Ncam = seq.size();
    vector<object_trj_t> & trlet_list=oi.trlet_list;
    int nobj = trlet_list.size();
    int num_new_obj = detected_rects(0).size1();
    int T = seq[0].size();
    int np = oi.model.size();

    int num_scales = P.scales.size();

    //std::cout<<"detected_rects="<<detected_rects<<std::endl;

    for(int oo=0; oo<num_new_obj; ++oo)
    {
	int nn = oi.curr_num_obj + oo;

	trlet_list(nn).startt = tt;
	trlet_list(nn).endt = tt;
	trlet_list(nn).state = 1;
	trlet_list(nn).trj = vector<matrix<float> >(Ncam);
	for(int cam=0; cam<Ncam; ++cam)
	{
	    trlet_list(nn).trj(cam) = scalar_matrix<float>(T, 4, 0);
	}
	trlet_list(nn).trj_3d = scalar_matrix<float>(T, 2, 0);

	trlet_list(nn).hist_p = vector<matrix<float> >(Ncam);
	trlet_list(nn).hist_q = vector<matrix<float> >(Ncam);

	trlet_list(nn).fscores = vector<matrix<float> >(Ncam);
	trlet_list(nn).scores = scalar_matrix<float>(Ncam, T, 0);

	vector<candidate_array<Float> > cand_array(Ncam);
	for(int cam=0; cam<Ncam; ++cam)
	{

	    trlet_list(nn).fscores(cam) = scalar_matrix<float>(np*2, T, 0);

	    float w = detected_rects(cam)(oo, 2)-detected_rects(cam)(oo, 0);
	    float h = detected_rects(cam)(oo, 3)-detected_rects(cam)(oo, 1);
	    row(trlet_list(nn).trj(cam), tt) = row(detected_rects(cam), oo);

	    matrix<float> rects;
	    compute_part_rects(detected_rects(cam)(oo, 0), detected_rects(cam)(oo, 1),
			  w, h, oi.model, rects);

	    pmodel_t pmodel;

	    vector<float> br(row(detected_rects(cam), oo));
	    rects_to_pmodel_geom(br, gi.horiz_mean, pmodel);
	    oi.pmodel_list(cam, nn) = pmodel;

	    //collect_sift(grd(cam), );
	    matrix<float> hist_p, hist_q;
	    collect_hist(images(cam), rects, hist_p, hist_q);
	    trlet_list(nn).hist_p(cam) = hist_p;
	    trlet_list(nn).hist_q(cam) = hist_q;

	    matrix<Float> cand_rects;
	    vector<Float> cand_scale;
	    matrix<int> cand_ijs;

	    if(0==world.rank())
	    {

		std::vector<float> sxr, syr;
		for(float v=-P.xrange/2; v<=P.xrange/2; v+=P.xstep)
		{
		    sxr.push_back(v);
		}
		for(float v=-P.yrange/2; v<=P.yrange/2; v+=P.ystep)
		{
		    syr.push_back(v);
		}
		vector<float> xr(sxr.size()), yr(syr.size());
		std::copy(sxr.begin(), sxr.end(), xr.begin());
		std::copy(syr.begin(), syr.end(), yr.begin());

		float feetx = (trlet_list(nn).trj(cam)(tt, 0)
			       +trlet_list(nn).trj(cam)(tt, 2))/2;
		float feety = trlet_list(nn).trj(cam)(tt, 3);


		enumerate_rects_inpoly(images(cam), oi.pmodel_list(cam, nn),
				       feetx, feety,
				       xr, yr, P.scales, gi.horiz_mean, gi.horiz_sig,
				       gi.polys_im(tt, cam),
				       cand_rects, cand_scale,
				       cand_ijs, cand_array(cam));

	    }

	    mpi::broadcast(world, cand_rects, 0);

	    real_timer_t timer;
	    vector<Float> cand_hist_score(cand_rects.size1());
	    matrix<Float> hist_fscores;

	    range rrank(world.rank()*cand_rects.size1()/world.size(), 
			(world.rank()+1)*cand_rects.size1()/world.size());
	    matrix<Float> cand_rects_rank(project(cand_rects, rrank, range(0, 4)));
	    vector<Float> cand_hist_score_rank;
	    matrix<Float> hist_fscores_rank;
	    get_cand_hist_score(images(cam), oi.model, P.logp1, P.logp2,
				trlet_list(nn).hist_p(cam),
				trlet_list(nn).hist_q(cam),
				cand_rects_rank,
				cand_hist_score_rank, hist_fscores_rank);
	    if(world.rank()==0)
	    {
		std::vector<vector<Float> > v1;
		std::vector<matrix<Float> > v2;
		mpi::gather(world, cand_hist_score_rank, v1, 0);
		mpi::gather(world, hist_fscores_rank, v2, 0);
		hist_fscores = matrix<Float>(cand_rects.size1(),
					     hist_fscores_rank.size2());
		for(int r=0; r<world.size(); ++r)
		{
		    int start = r*cand_rects.size1()/world.size();
		    for(int vv=0; vv<v1[r].size(); ++vv)
		    {
			cand_hist_score(start+vv) = v1[r](vv);
		    }
		    for(int vv=0; vv<v2[r].size1(); ++vv)
		    {
			row(hist_fscores, start+vv) = row(v2[r], vv);
		    }
		}
	    }
	    else
	    {
		mpi::gather(world, cand_hist_score_rank, 0);
		mpi::gather(world, hist_fscores_rank, 0);
	    }

	    mpi::broadcast(world, cand_hist_score, 0);
	    mpi::broadcast(world, hist_fscores, 0);


	    vector<Float> cand_score=cand_hist_score;
	    if(0==world.rank())
	    std::cout<<"\t\t"<<cand_rects.size1()<<" rects, \tget_cand_hist_score time:"
		     <<timer.elapsed()/1000.0f<<"s."<<std::endl;

	    if(0==world.rank())
	    {
		int idx_max = std::max_element(cand_score.begin(), cand_score.end())
		    - cand_score.begin();

		column(trlet_list(nn).fscores(cam), tt) = row(hist_fscores, idx_max);
		trlet_list(nn).scores(cam, tt) = cand_score(idx_max);
		cand_array(cam).fill_score(cand_score, cand_ijs);
	    }
	    mpi::broadcast(world, cand_array(cam), 0);
	    mpi::broadcast(world, trlet_list(nn).scores(cam, tt), 0);
	    vector<Float> fscore_col;
	    if(0==world.rank())
	    {
		fscore_col = column(trlet_list(nn).fscores(cam), tt);
	    }
	    mpi::broadcast(world, fscore_col, 0);
	    if(0!=world.rank())
	    {
		column(trlet_list(nn).fscores(cam), tt) = fscore_col;
	    }


	}//end for cam

	int best_y, best_x, best_s;
	if(0==world.rank())
	{
	    ground_scoremap_t<Float> grd_scoremap;
	    combine_ground_score(tt, cand_array, grd_scoremap, gi);
	    grd_scoremap.peak(best_y, best_x, best_s);	
	}
	mpi::broadcast(world, best_y, 0);
	mpi::broadcast(world, best_x, 0);

	trlet_list(nn).trj_3d(tt, 0) = best_x;
	trlet_list(nn).trj_3d(tt, 1) = best_y;

	for(int cam=0; cam<Ncam; ++cam)
	{
	    vector<Float> trj_row(4);

	    if(0==world.rank())
	    {
		vector<double> bx(1), by(1), ix, iy;
		bx <<= best_x; by <<= best_y;
		apply_homography(gi.grd2img(tt, cam), bx, by, ix, iy);
		float hpre = oi.pmodel_list(cam, nn).hpre;
		float cur_fy = iy(0);
		float cur_fx = ix(0);
		float cur_hy = gi.horiz_mean+hpre*(cur_fy-gi.horiz_mean);
		float ds = P.scales(best_s)*(cur_fy-cur_hy)/oi.pmodel_list(cam, nn).bh;
		float ww = ds*oi.pmodel_list(cam, nn).bw;
		float hh = cur_fy - cur_hy;

		trj_row <<= (cur_fx-ww/2), cur_hy, (cur_fx+ww/2), cur_fy;
	    }
	    mpi::broadcast(world, trj_row, 0);
	    row(trlet_list(nn).trj(cam), tt) = trj_row;


	}//endfor cam

    }//endfor oo

    oi.curr_num_obj += num_new_obj;
}
示例#23
0
 const Vector4T<T>& operator[](int i) const{ return row(i); }
示例#24
0
void initialize_new_objects(parameter_t const& P,  directory_structure_t const& ds,
			    geometric_info_t const& gi, object_info_t& oi,
			    vector<std::vector<std::string> > const &seq, int tt,
			    vector<CImg<unsigned char> > const& images,
			    vector<matrix<float> > const& grd,
			    vector<matrix<float> >& detected_rects)
{
    int Ncam = seq.size();
    vector<object_trj_t> & trlet_list=oi.trlet_list;
    int nobj = trlet_list.size();
    int num_new_obj = detected_rects(0).size1();
    int T = seq[0].size();
    int np = oi.model.size();

    int num_scales = P.scales.size();

    for(int oo=0; oo<num_new_obj; ++oo)
    {
	int nn = oi.curr_num_obj + oo;


	trlet_list(nn).startt = tt;
	trlet_list(nn).endt = tt;
	trlet_list(nn).state = 1;
	trlet_list(nn).trj = vector<matrix<float> >(Ncam);
	for(int cam=0; cam<Ncam; ++cam)
	{
	    trlet_list(nn).trj(cam) = scalar_matrix<float>(T, 4, 0);
	}
	trlet_list(nn).trj_3d = scalar_matrix<float>(T, 2, 0);

	trlet_list(nn).hist_p = vector<matrix<float> >(Ncam);
	trlet_list(nn).hist_q = vector<matrix<float> >(Ncam);

	trlet_list(nn).fscores = vector<matrix<float> >(Ncam);
	trlet_list(nn).scores = scalar_matrix<float>(Ncam, T, 0);

	vector<candidate_array<Float> > cand_array(Ncam);

	for(int cam=0; cam<Ncam; ++cam)
	{

	    trlet_list(nn).fscores(cam) = scalar_matrix<float>(np*2, T, 0);

	    float w = detected_rects(cam)(oo, 2)-detected_rects(cam)(oo, 0);
	    float h = detected_rects(cam)(oo, 3)-detected_rects(cam)(oo, 1);
	    row(trlet_list(nn).trj(cam), tt) = row(detected_rects(cam), oo);

	    matrix<float> rects;
	    compute_part_rects(detected_rects(cam)(oo, 0), detected_rects(cam)(oo, 1),
			  w, h, oi.model, rects);

	    pmodel_t pmodel;

	    vector<float> br(row(detected_rects(cam), oo));
	    rects_to_pmodel_geom(br, gi.horiz_mean, pmodel);
	    oi.pmodel_list(cam, nn) = pmodel;

	    //collect_sift(grd(cam), );
	    matrix<float> hist_p, hist_q;
	    collect_hist(images(cam), rects, hist_p, hist_q);
	    trlet_list(nn).hist_p(cam) = hist_p;
	    trlet_list(nn).hist_q(cam) = hist_q;


	    std::vector<float> sxr, syr;
	    for(float v=-P.xrange/2; v<=P.xrange/2; v+=P.xstep)
	    {
		sxr.push_back(v);
	    }
	    for(float v=-P.yrange/2; v<=P.yrange/2; v+=P.ystep)
	    {
		syr.push_back(v);
	    }
	    vector<float> xr(sxr.size()), yr(syr.size());
	    std::copy(sxr.begin(), sxr.end(), xr.begin());
	    std::copy(syr.begin(), syr.end(), yr.begin());

	    float feetx = (trlet_list(nn).trj(cam)(tt, 0)
			   +trlet_list(nn).trj(cam)(tt, 2))/2;
	    float feety = trlet_list(nn).trj(cam)(tt, 3);

	    matrix<Float> cand_rects;
	    vector<Float> cand_scale;
	    matrix<int> cand_ijs;

	    enumerate_rects_inpoly(images(cam), oi.pmodel_list(cam, nn),
				   feetx, feety,
				   xr, yr, P.scales, gi.horiz_mean, gi.horiz_sig,
				   gi.polys_im(cam),
				   cand_rects, cand_scale,
				   cand_ijs, cand_array(cam));


	    vector<Float> cand_hist_score;
	    matrix<Float> hist_fscores;

	    real_timer_t timer;
	    get_cand_hist_score(images(cam), oi.model, P.logp1, P.logp2,
				trlet_list(nn).hist_p(cam),
				trlet_list(nn).hist_q(cam),
				cand_rects,
				cand_hist_score, hist_fscores);

	    vector<Float> cand_score=cand_hist_score;
	    std::cout<<"\t\t"<<cand_rects.size1()<<" rects, \tget_cand_hist_score time:"
		     <<timer.elapsed()/1000.0f<<"s."<<std::endl;

	    int idx_max = std::max_element(cand_score.begin(), cand_score.end())
		- cand_score.begin();

	    column(trlet_list(nn).fscores(cam), tt) = row(hist_fscores, idx_max);
	    trlet_list(nn).scores(cam, tt) = cand_score(idx_max);
	    cand_array(cam).fill_score(cand_score, cand_ijs);


	}//end for cam

	real_timer_t timer;

	ground_scoremap_t<Float> grd_scoremap;
	combine_ground_score(cand_array, grd_scoremap, gi);
	int best_y, best_x, best_s;

	grd_scoremap.peak(best_y, best_x, best_s);	


	for(int cam=0; cam<Ncam; ++cam)
	{
	    vector<double> bx(1), by(1), ix, iy;
	    bx <<= best_x; by <<= best_y;
	    apply_homography(gi.grd2img(cam), bx, by, ix, iy);
	    float hpre = oi.pmodel_list(cam, nn).hpre;
	    float cur_fy = iy(0);
	    float cur_fx = ix(0);
	    float cur_hy = gi.horiz_mean+hpre*(cur_fy-gi.horiz_mean);
	    float ds = P.scales(best_s)*(cur_fy-cur_hy)/oi.pmodel_list(cam, nn).bh;
	    float ww = ds*oi.pmodel_list(cam, nn).bw;
	    float hh = cur_fy - cur_hy;

	    vector<Float> tmp(4);
	    tmp <<= (cur_fx-ww/2), cur_hy, (cur_fx+ww/2), cur_fy;
	    row(trlet_list(nn).trj(cam), tt) = tmp;

	    //std::cout<<"trlet_list(nn).trj(cam)(tt, :)="
	    //     <<row(trlet_list(nn).trj(cam), tt)<<std::endl;

	}//endfor cam

    }//endfor oo

    oi.curr_num_obj += num_new_obj;
}
示例#25
0
文件: fsm.cpp 项目: kartynnik/pire
void Fsm::DumpState(yostream& s, size_t state) const
{
	// Fill in a 'row': Q -> exp(V) (for current state)
	yvector< ybitset<MaxChar> > row(Size());
	for (TransitionRow::const_iterator rit = m_transitions[state].begin(), rie = m_transitions[state].end(); rit != rie; ++rit)
		for (StatesSet::const_iterator sit = rit->second.begin(), sie = rit->second.end(); sit != sie; ++sit) {
			if (*sit >= Size()) {
				std::cerr << "WTF?! Transition from " << state << " on letter " << rit->first << " leads to non-existing state " << *sit << "\n";
				YASSERT(false);
			}
			if (Letters().Contains(rit->first)) {
				const yvector<Char>& letters = Letters().Klass(Letters().Representative(rit->first));
				for (yvector<Char>::const_iterator lit = letters.begin(), lie = letters.end(); lit != lie; ++lit)
					row[*sit].set(*lit);
			} else
				row[*sit].set(rit->first);
		}

	bool statePrinted = false;
	// Display each destination state
	for (yvector< ybitset<MaxChar> >::iterator rit = row.begin(), rie = row.end(); rit != rie; ++rit) {
		unsigned begin = 0, end = 0;

		ystring delimiter;
		ystring label;
		if (rit->test(Epsilon)) {
			label += delimiter + CharDump(Epsilon);
			delimiter = " ";
		}
		if (rit->test(BeginMark)) {
			label += delimiter + CharDump(BeginMark);
			delimiter = " ";
		}
		if (rit->test(EndMark)) {
			label += delimiter + CharDump(EndMark);
			delimiter = " ";
		}
		unsigned count = 0;
		for (unsigned i = 0; i < 256; ++i)
			if (rit->test(i))
				++count;
		if (count != 0 && count != 256) {
			label += delimiter + "[";
			bool complementary = (count > 128);
			if (count > 128)
				label += "^";
			while (begin < 256) {
				for (begin = end; begin < 256 && (rit->test(begin) == complementary); ++begin)
					;
				for (end = begin; end < 256 && (rit->test(end) == !complementary); ++end)
					;
				if (begin + 1 == end) {
					label += CharDump(begin);
					delimiter = " ";
				} else if (begin != end) {
					label += CharDump(begin) + "-" + (CharDump(end-1));
					delimiter = " ";
				}
			}
			label += "]";
			delimiter = " ";
		} else if (count == 256) {
			label += delimiter + ".";
			delimiter = " ";
		}
		if (!label.empty()) {
			if (!statePrinted) {
				s << "    " << state << "[shape=\"" << (IsFinal(state) ? "double" : "") << "circle\",label=\"" << state;
				Tags::const_iterator ti = tags.find(state);
				if (ti != tags.end())
					s << " (tags: " << ti->second << ")";
				s << "\"]\n";
				if (Initial() == state)
					s << "    \"initial\" -> " << state << '\n';
				statePrinted = true;
			}
			s << "    " << state << " -> " << std::distance(row.begin(), rit) << "[label=\"" << label;

			// Display outputs
			Outputs::const_iterator oit = outputs.find(state);
			if (oit != outputs.end()) {
				Outputs::value_type::second_type::const_iterator oit2 = oit->second.find(std::distance(row.begin(), rit));
				if (oit2 == oit->second.end())
					;
				else {
					yvector<int> payload;
					for (unsigned i = 0; i < sizeof(oit2->second) * 8; ++i)
						if (oit2->second & (1ul << i))
							payload.push_back(i);
					if (!payload.empty())
						s << " (outputs: " << Join(payload.begin(), payload.end(), ", ") << ")";
				}
			}

			s << "\"]\n";
		}
	}

	if (statePrinted)
		s << '\n';
}
static gboolean
ring_notify_show_text_message(ContactMethod *cm, const QModelIndex& idx)
{
    g_return_val_if_fail(idx.isValid() && cm, FALSE);
    gboolean success = FALSE;

    auto title = g_markup_printf_escaped(C_("Text message notification", "%s says:"), idx.data(static_cast<int>(Ring::Role::Name)).toString().toUtf8().constData());
    auto body = g_markup_escape_text(idx.data(Qt::DisplayRole).toString().toUtf8().constData(), -1);

    NotifyNotification *notification_new = nullptr;
    NotifyNotification *notification_old = nullptr;

    /* try to get the previous notification */
    auto chat_table = ring_notify_get_chat_table();
    auto list = (GList *)g_hash_table_lookup(chat_table, cm);
    if (list)
        notification_old = (NotifyNotification *)list->data;

    /* we display chat notifications in different ways to suit different notification servers and
     * their capabilities:
     * 1. if the server doesn't support appending (eg: Notification Daemon) then we update the
     *    previous notification (if exists) with new text; otherwise it takes we have many
     *    notifications from the same person... we don't concatinate the old messages because
     *    servers which don't support append usually don't support multi line bodies
     * 2. the notify-osd server supports appending; however it doesn't clear the old notifications
     *    on demand, which means in our case that chat messages which have already been read could
     *    still be displayed when a new notification is appended, thus in this case, we update
     *    the old notification body manually to only contain the unread messages
     * 3. the 3rd case is that the server supports append but is not notify-osd, then we simply use
     *    the append feature
     */

    if (notification_old && !server_info.append) {
        /* case 1 */
        notify_notification_update(notification_old, title, body, nullptr);
        notification_new = notification_old;
    } else if (notification_old && g_strcmp0(server_info.name, SERVER_NOTIFY_OSD) == 0) {
        /* case 2 */
        /* print up to MAX_NOTIFICATIONS unread messages */
        int msg_count = 0;
        auto idx_next = idx.sibling(idx.row() - 1, idx.column());
        auto read = idx_next.data(static_cast<int>(Media::TextRecording::Role::IsRead)).toBool();
        while (idx_next.isValid() && !read && msg_count < MAX_NOTIFICATIONS) {

            auto body_prev = body;
            body = g_markup_printf_escaped("%s\n%s", body_prev, idx_next.data(Qt::DisplayRole).toString().toUtf8().constData());
            g_free(body_prev);

            idx_next = idx_next.sibling(idx_next.row() - 1, idx_next.column());
            read = idx_next.data(static_cast<int>(Media::TextRecording::Role::IsRead)).toBool();
            ++msg_count;
        }

        notify_notification_update(notification_old, title, body, nullptr);

        notification_new = notification_old;
    } else {
        /* need new notification for case 1, 2, or 3 */
        notification_new = notify_notification_new(title, body, nullptr);

        /* track in hash table */
        auto list = (GList *)g_hash_table_lookup(chat_table, cm);
        list = g_list_append(list, notification_new);
        g_hash_table_replace(chat_table, cm, list);

        /* get photo */
        QVariant var_p = GlobalInstances::pixmapManipulator().callPhoto(
            cm, QSize(50, 50), false);
        std::shared_ptr<GdkPixbuf> photo = var_p.value<std::shared_ptr<GdkPixbuf>>();
        notify_notification_set_image_from_pixbuf(notification_new, photo.get());

        /* normal priority for messages */
        notify_notification_set_urgency(notification_new, NOTIFY_URGENCY_NORMAL);

        /* remove the key and value from the hash table once the notification is
         * closed; note that this will also unref the notification */
        g_signal_connect(notification_new, "closed", G_CALLBACK(notification_closed), cm);

        /* if the notification server supports actions, make the default action to show the chat view */
        if (server_info.actions) {
            notify_notification_add_action(notification_new,
                                           "default",
                                           C_("notification action name", "Show"),
                                           (NotifyActionCallback)ring_notify_show_cm,
                                           cm,
                                           nullptr);
        }
    }

    GError *error = nullptr;
    success = notify_notification_show(notification_new, &error);
    if (!success) {
        g_warning("failed to show notification: %s", error->message);
        g_clear_error(&error);
    }

    g_free(title);
    g_free(body);

    return success;
}
示例#27
0
void NormalEstimator::computePCA(cv::Mat& oVec, cv::Mat& eVec,cv::Mat& valVec){
	//
	int dim = oVec.size().width;
	int oCnt = oVec.size().height;
	eVec = cv::Mat(dim,dim,CV_64FC1);
	valVec = cv::Mat(dim,1,CV_64FC1);

	//compute the mean
	cv::Mat row(1,dim,CV_64FC1);
	row = 0.0f;
	for (int i = 0; i < oCnt; i++)
	{
		row = row + oVec.row(i);
	}
	row /= oCnt;
	//for (int i = 0; i < dim; i++)
	//{
	//	std::cout << row.at<double>(0,i) << " " ;
	//}
	//std::cout << std::endl;
	//getchar();
	//subtraction
	for (int i = 0; i < oCnt; i++)
	{
		for (int j = 0; j < dim; j++)
		{
			oVec.at<double>(i,j) = oVec.at<double>(i,j) - row.at<double>(0,j);
		}
	}
	//
	cv::Mat extProd(dim,dim,CV_64FC1);
	extProd = 0.0f;

	cv::Mat oVecT(dim,1,CV_64FC1);

	//for (int i = 0; i < oCnt; i++)
	//{
	//	for (int j = 0; j < dim; j++)
	//	{
	//		std::cout << oVec.at<double>(i,j) << " ";
	//	}
	//	std::cout << std::endl;
	//}
	//getchar();

	for (int i = 0; i < oCnt; i++)
	{
		cv::transpose(oVec.row(i),oVecT);
		extProd = extProd +  (oVecT * oVec.row(i));
		////print the product
		//for (int i1 = 0; i1 < dim ;i1++)
		//{
		//	for (int j1 = 0; j1 < dim; j1++)
		//	{
		//		std::cout << tmp.at<double>(i1,j1) << " ";
		//	}
		//	std::cout << std::endl;
		//}
		//getchar();

	}
	extProd /= oCnt;
	//for (int i = 0; i < dim ;i++)
	//{
	//	for (int j = 0; j < dim; j++)
	//	{
	//		std::cout << extProd.at<double>(i,j) << " ";
	//	}
	//	std::cout << std::endl;
	//}
	//getchar();
	cv::eigen(extProd,valVec,eVec);
	//

}
示例#28
0
/**
 * Get next token in the current string expr.
 * Uses the ExpParser data expr, e, token, t, token_type and err
 */
void ExpParser::getToken()
{
    token_type = NOTHING;
    char* t;           // points to a character in token
    t = token;         // let t point to the first character in token
    *t = '\0';         // set token empty

    //printf("\tgetToken e:{%c}, ascii=%i, col=%i\n", *e, *e, e-expr);

    // skip over whitespaces
    while (*e == ' ' || *e == '\t')     // space or tab
    {
        e++;
    }

    // check for end of expression
    if (*e == '\0')
    {
        // token is still empty
        token_type = DELIMETER;
        return;
    }

    // check for minus
    if (*e == '-')
    {
        token_type = DELIMETER;
        *t = *e;
        e++;
        t++;
        *t = '\0';  // add a null character at the end of token
        return;
    }

    // check for parentheses
    if (*e == '(' || *e == ')')
    {
        token_type = DELIMETER;
        *t = *e;
        e++;
        t++;
        *t = '\0';
        return;
    }

    // check for operators (delimeters)
    if (isDelimeter(*e))
    {
        token_type = DELIMETER;
        while (isDelimeter(*e))
        {
            *t = *e;
            e++;
            t++;
        }
        *t = '\0';  // add a null character at the end of token
        return;
    }

    // check for a value
    if (isDigitDot(*e))
    {
        token_type = NUMBER;
        while (isDigitDot(*e))
        {
            *t = *e;
            e++;
            t++;
        }

        // check for scientific notation like "2.3e-4" or "1.23e50"
        if (toupper(*e) == 'E')
        {
            *t = *e;
            e++;
            t++;

            if (*e == '+' || *e == '-')
            {
                *t = *e;
                e++;
                t++;
            }

            while (isDigit(*e))
            {
                *t = *e;
                e++;
                t++;
            }
        }

        *t = '\0';
        return;
    }

    // check for variables or functions
    if (isAlpha(*e))
    {
        while (isAlpha(*e) || isDigit(*e))
        //while (isNotDelimeter(*e))
        {
            *t = *e;
            e++;
            t++;
        }
        *t = '\0';  // add a null character at the end of token

        // check if this is a variable or a function.
        // a function has a parentesis '(' open after the name
        char* e2 = NULL;
        e2 = e;

        // skip whitespaces
        while (*e2 == ' ' || *e2 == '\t')     // space or tab
        {
            e2++;
        }

        if (*e2 == '(')
        {
            token_type = FUNCTION;
        }
        else
        {
            token_type = VARIABLE;
        }
        return;
    }

    // something unknown is found, wrong characters -> a syntax error
    token_type = UNKNOWN;
    while (*e != '\0')
    {
        *t = *e;
        e++;
        t++;
    }
    *t = '\0';
    throw Error(row(), col(), 1, token);

    return;
}
示例#29
0
MATHBASE_API 
void _JordanGaussCR( CDSRMMatrix<CDSRReal> *pA, CDSRMVector<CDSRReal> *pB, CDSRMVector<CDSRReal> *pX )
{
	if( pA->n_row() != pA->n_column() )
		throw "The matrix is not square";
	if( pA->n_row() != (long) pB->size() )
		throw "Internal problem - sizes of the source and destination matrix are not equal";

	long i, j, k;
	CDSRReal value;
	CDSRMMatrix<CDSRReal> matrix( (*pA) );
	CDSRMVector<CDSRReal> vector( (*pB) );
	CDSRMVector<long> row( pA->n_row() );
	CDSRMVector<long> col( pA->n_row() );

	pX->resize( pB->size() );

	for( i = 0; i < pA->n_row(); i++ )
		col[ i ] = row[ i ] = i;

	for( i = 0; i < pA->n_row(); i++ )
	{
		if( IsNull( matrix( row[ i ], col[ i ] ) ) )
			_IndexCR(i, &matrix, &row, &col );

		for( k = i; k < pA->n_row(); k++ )
		{
			value = matrix( row[ k ], col[ i ] );
			if( IsNotNull( value ) && IsNotOne( value ) )
			{
				vector[ row[ k ] ] /= value;
				for( j = i + 1; j < pA->n_row(); j++ )
					matrix( row[ k ], col[ j ] ) /= value;
				matrix( row[ k ], col[ i ] ) = 1.0;
			}
		}

		for( k = i + 1; k < pA->n_row(); k++ )
		{
			value = matrix( row[ k ], col[ i ] );
			if( IsNotNull( value ) )
			{
				vector[ row[ k ] ] -= vector[ row[ i ] ];
				for( j = i + 1; j < pA->n_row(); j++ )
					matrix( row[ k ], col[ j ] ) -= matrix( row[ i ], col[ j ] );
				matrix( row[ k ], col[ i ] ) = 0.0;
			}
		}
	}

	for( i = pA->n_row() - 1; i > 0; i-- )
	{
		for( k = 0; k < i + 1; k++ )
		{
			value = matrix( row[ k ], col[ i ] );
			if( IsNotNull( value ) && IsNotOne( value ) )
			{
				vector[ row[ k ] ] /= value;
	   			for( j = k; j < i; j++ )
   					matrix( row[ k ], col[ j ] ) /= value;
				matrix( row[ k ], col[ i ] ) = 1.0;
			}
		}

		for( k = 0; k < i; k++ )
		{
			value = matrix( row[ k ], col[ i ] );
			if( IsNotNull( value ) )
			{
				vector[ row[ k ] ] -= vector[ row[ i ] ];
				matrix( row[ k ], col[ i ] ) = 0.0;
			}
		}
	}

	vector[ row[ 0 ] ] /= matrix( row[ 0 ], col[ 0 ] );
	matrix( row[ 0 ], col[ 0 ] ) = 1.0;

	for( i = 0; i < pA->n_row(); i++ )
		( *pX )[ col[ i ] ] = vector[ row[ i ] ];
}
示例#30
0
float Matrix4::determinant() const {
    // Determinant is the dot product of the first row and the first row
    // of cofactors (i.e. the first col of the adjoint matrix)
    return cofactor().row(0).dot(row(0));
}