예제 #1
0
void __ARG32_LOAD(U8 *src)
{
        wa(ARG32+3,src[3]);              // MSB
        wa(ARG32+2,src[2]);
        wa(ARG32+1,src[1]);
        wa(ARG32+0,src[0]);
}
    Disposable<Array> qrSolve(const Matrix& a, const Array& b,
                              bool pivot, const Array& d) {
        const Size m = a.rows();
        const Size n = a.columns();

        QL_REQUIRE(b.size() == m, "dimensions of A and b don't match");
        QL_REQUIRE(d.size() == n || d.empty(),
                   "dimensions of A and d don't match");

        Matrix q(m, n), r(n, n);

        std::vector<Size> lipvt = qrDecomposition(a, q, r, pivot);

        boost::scoped_array<int> ipvt(new int[n]);
        std::copy(lipvt.begin(), lipvt.end(), ipvt.get());

        Matrix rT = transpose(r);

        boost::scoped_array<Real> sdiag(new Real[n]);
        boost::scoped_array<Real> wa(new Real[n]);

        Array ld(n, 0.0);
        if (!d.empty()) {
            std::copy(d.begin(), d.end(), ld.begin());
        }

        Array x(n);
        Array qtb = transpose(q)*b;

        MINPACK::qrsolv(n, rT.begin(), n, ipvt.get(),
                        ld.begin(), qtb.begin(),
                        x.begin(), sdiag.get(), wa.get());

        return x;
    }
int main(int argc, char* argv[])
{
    FILE* in = fopen(argv[1], "r");
    fscanf(in, "%d", &N);

    if (N == 1)
        ok10();

    while (true)
    {
        guessesCount++;
        if (guessesCount > MAX_GUESSES)
            wa();

        scanf("%d", &guess);

        if (guess == N)
        {
            printf("yes\n");
            fflush(stdout);
            ac();
        }
        else if (guess < N)
            printf("too_low\n");
        else
            printf("too_high\n");
        fflush(stdout);
    }
}
예제 #4
0
파일: SoSFNode.cpp 프로젝트: Alexpux/Coin3D
// Export node.
void
SoSFNode::writeValue(SoOutput * out) const
{
  // NB: This code is common for SoSFNode, SoSFPath and SoSFEngine.
  // That's why we check the base type before writing.
  SoBase * base = this->getValue();
  if (base) {
    if (base->isOfType(SoNode::getClassTypeId())) {
      coin_assert_cast<SoNode *>(base)->writeInstance(out);
    }
    else if (base->isOfType(SoPath::getClassTypeId())) {
      SoWriteAction wa(out);
      wa.continueToApply(coin_assert_cast<SoPath *>(base));
    }
    else if (base->isOfType(SoEngine::getClassTypeId())) {
      coin_assert_cast<SoEngine *>(base)->writeInstance(out);
    }
    else {
      assert(0 && "strange internal error");
    }
  }
  else {
    // This actually works for both ASCII and binary formats.
    out->write("NULL");
  }
}
예제 #5
0
void ReadWaterCoord(waterVec& wv){
     ifstream myfile("EcosystemFile.txt");
     int n = ReadWaterAreas();
     string line;
     vector <int> values(4);
     if (myfile.is_open()){
        for (int i = 0; i < n + 3; i++){
            getline(myfile, line);
            if (i > 2){
                for (int k = 0; k < line.size(); k++){
                    if (line[k] == ',') line[k] = ' ';
                }
                istringstream iss(line);
                for (int j = 0; j < 4; j++){
                    int val;
                    iss >> val;
                    values[j] = val;
                }
                shared_ptr<WaterArea> wa (new WaterArea(values[0], values[1], values[2], values[3]));
                try {
                   if (wa->HasRightInput()) wv.push_back(wa);
                }
                catch (AreaException& e){
                    cout<<e.what()<<endl;
                }
           }
        }
     }
     cout<<"Water areas: "<<wv.size()<<endl;
}
예제 #6
0
void LexOrFold(bool foldOrLex, unsigned int startPos, unsigned int length, int initStyle,
               char *words[], WindowID window, char *props)
{
    // Create and initialize the WindowAccessor (including contained PropSet)
    PropSetSimple ps;
    ps.SetMultiple(props);
    WindowAccessor wa(window, ps);

    //  Create and initialize WordList(s).
    //  If you have an extremely large word file, or lots of styling rules you may want to speed
    //  up processing by storing the wordlists instead of reprocessing them on each call.
    int nWL = 0;
    for (; words[nWL]; nWL++) ;	// count # of WordList PTRs needed
    WordList** wl = new WordList* [nWL + 1];// alloc WordList PTRs
    int i = 0;
    for (; i < nWL; i++) {
        wl[i] = new WordList();	// (works or THROWS bad_alloc EXCEPTION)
        wl[i]->Set(words[i]);
    }
    wl[i] = 0;

    //  Call the internal folding and styling functions.
    // foldOrLex is false for lex and true for fold
    if (foldOrLex) {

        // This is a nice helpful routine to back up a line to fix broken folds.
        int lineCurrent = wa.GetLine(startPos);
        if (lineCurrent > 0) {
            lineCurrent--;
            int newStartPos = wa.LineStart(lineCurrent);
            length += startPos - newStartPos;
            startPos = newStartPos;
            initStyle = 0;
            if (startPos > 0) {
                initStyle = wa.StyleAt(startPos - 1);
            }
        }

        Fold_Doc(startPos, length, initStyle, wl, wa);

    }
    else {

        //  You may want to put a routine here to backtrack past leaking styles, typically
        //  multiline styles, or just put such logic in the Colour_Doc function itself.  Just
        //  be sure to do it prior to creating your Style Context.

        Colourise_Doc(startPos, length, initStyle, wl, wa);

    }

    //  The flush function is what actually finalizes settings the styles you just coloured.
    wa.Flush();

    // Clean up the wordlists before leaving.
    for (i = nWL - 1; i >= 0; i--)
        delete wl[i];
    delete [] wl;
}
예제 #7
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Worker wa("COM3");
    int ax = a.exec();
    qDebug("exit");
    return ax;
}
예제 #8
0
int wa(int n)
{
    if(n <= 1) {
        return 1;
    } else {
        return n + wa(n - 1);
    }
}
예제 #9
0
int main()
{
    int n, s;

    scanf("%d", &n);
    s = wa(n);
    printf("%d\n", s);
}
예제 #10
0
// IEEE ARG LOAD/STORE
void __FP_LOAD_IEEE_ARG(U8 *src)
{
    unsigned char tr[TR_SIZE];
    double r;
	double *d;
#ifndef FPBIG
        wa(ARG32+3,src[3]);              // MSB
        wa(ARG32+2,src[2]);
        wa(ARG32+1,src[1]);
        wa(ARG32+0,src[0]);
		_SAVE();
		my_ex_cmd(_IEEE_TO_TRarg);
		_RESTORE();
#else
	d = (double *) src;
    d2tr((double) *d,tr,0);
    __FP_LOAD_TR_ARG(tr);
#endif
}
예제 #11
0
int main(void)
{
	int n,m;

	printf("input = "); scanf("%d%d",&n,&m);

	printf("%dから%dまでの和 : %d\n",n,m,wa(n,m));

	return 0;
}
예제 #12
0
int main(int argc, char **argv) {

  correct_output = fopen(argv[2], "r");
  program_output = fopen(argv[3], "r");

  double a, b;
  while (fscanf(correct_output, "%lf", &a) > 0) {
    if (fscanf(program_output, "%lf", &b) <= 0) {
      wa();
      break;
    }
    if (!eq(a, b)) {
      wa();
      break;
    }
  }

  ac();
}
예제 #13
0
void
SoSFPath::writeValue(SoOutput *out) const
//
////////////////////////////////////////////////////////////////////////
{
    if (value != NULL) {
	SoWriteAction	wa(out);
	wa.continueToApply(value);
    }
    else
	out->write("NULL");
}
예제 #14
0
파일: grader.c 프로젝트: blmarket/icpc
void compile_set() {
    if (compiled) {
        wa();
    }
    compiled = 1;
    struct node* compiledSet = create();
    char* element = (char*)malloc(n + 1);
    element[n] = 0;
    char* compiled = (char*)malloc(n + 1);
    compiled[n] = 0;
    compile(set, 0, compiledSet, element, compiled);
    set = compiledSet;
}
예제 #15
0
ImagePtr	SimCamera::getImage() {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "retrieving image");
	// check whether the image is ready
	switch (exposureStatus()) {
	case CcdState::idle:
		debug(LOG_ERR, DEBUG_LOG, 0, "camera idle, cannot get image");
		throw std::runtime_error("camera idle");
		break;
	case CcdState::exposed:
		break;
	case CcdState::exposing:
		await_exposure();
		break;
	case CcdState::cancelling:
		debug(LOG_ERR, DEBUG_LOG, 0, "cancelling is impossible");
		throw std::runtime_error("cannot happen");
		break;
	}
	exposurestart = -1;

	// complete any pending motions
	debug(LOG_DEBUG, DEBUG_LOG, 0, "complete movement up to now");
	{
		std::unique_lock<std::mutex>	lock(mutex);
		complete_movement();
	}

	// add base motion
	double	nowtime = Timer::gettime();
	x += vx * (nowtime - lastexposure);
	y += vy * (nowtime - lastexposure);
	lastexposure = nowtime;

	// create the image based on the current position parameters
	debug(LOG_DEBUG, DEBUG_LOG, 0, "creating 640x480 image");
	Image<unsigned short>	image(640, 480);
	// write image contents
	debug(LOG_DEBUG, DEBUG_LOG, 0, "drawing star at %f,%f", x, y);
	for (unsigned int xi = 0; xi < 640; xi++) {
		for (unsigned int yi = 0; yi < 480; yi++) {
			double	r = hypot(xi - x, yi - y);
			unsigned short	value = 10000 * exp(-r * r / 5);
			image.pixel(xi, yi) = value;
		}
	}
	// now extract the window defiend in the frame
	debug(LOG_DEBUG, DEBUG_LOG, 0, "extracting %s window",
		exposure.frame().toString().c_str());
	WindowAdapter<unsigned short>	wa(image, exposure.frame());
	return ImagePtr(new Image<unsigned short>(wa));
}
예제 #16
0
void
SoSFPath::countWriteRefs(SoOutput *out) const
//
////////////////////////////////////////////////////////////////////////
{
    // Do standard counting for field
    SoField::countWriteRefs(out);

    // Count path
    if (value != NULL) {
	SoWriteAction	wa(out);
	wa.continueToApply(value);
    }
}
예제 #17
0
// TR AC LOAD/STORE
void __FP_LOAD_TR_AC(U8 *src)
{
        wa(FPac_SIGN,src[5]);
        wa(FPac_EXP,src[4]);
        wa(AC32+3,src[3]);
        wa(AC32+2,src[2]);
        wa(AC32+1,src[1]);
        wa(AC32,src[0]);
}
예제 #18
0
// TR ARG LOAD/STORE
void __FP_LOAD_TR_ARG(U8 *src)
{
        wa(FParg_SIGN,src[5]);
        wa(FParg_EXP,src[4]);
        wa(ARG32+3,src[3]);
        wa(ARG32+2,src[2]);
        wa(ARG32+1,src[1]);
        wa(ARG32,src[0]);
}
예제 #19
0
int main()
{
  boost::owner_less<boost::shared_ptr<int> > comp;
  {
    boost::shared_ptr<int> x;
    boost::shared_ptr<int> y;
    boost::weak_ptr<int> w;
    BOOST_TEST(!(comp(x, w) || comp(w, x)));
  }
  {
    boost::shared_ptr<int> z((int*)0);
    boost::weak_ptr<int> w;
    BOOST_TEST(comp(z, w) || comp(w, z));
    {
      boost::shared_ptr<int> zz(z);
      w = boost::weak_ptr<int>(zz);
      BOOST_TEST(!(comp(z, zz) || comp(z, zz)));
      BOOST_TEST(!(comp(z, w) || comp(z, w)));
    }
    BOOST_TEST(!(comp(z, w) || comp(w, z)));
  }
  {
    boost::shared_ptr<int> x;
    boost::shared_ptr<int> z((int*)0);
    BOOST_TEST(comp(x, z) || comp(z, x));
  }
  {
    boost::shared_ptr<int> a((int*)0);
    boost::shared_ptr<int> b((int*)0);
    BOOST_TEST(comp(a, b) || comp(b, a));
    boost::weak_ptr<int> w(a);
    BOOST_TEST(!(comp(a, w) || comp(w, a)));
    BOOST_TEST(comp(b, w) || comp(w, b));
  }

  boost::owner_less<boost::weak_ptr<int> > weak_comp;
  {
    boost::shared_ptr<int> a((int*)0);
    boost::weak_ptr<int> wa(a);
    boost::shared_ptr<int> b((int*)0);
    boost::weak_ptr<int> wb(b);
    BOOST_TEST(!(weak_comp(a, wa) || weak_comp(wa, a)));
    BOOST_TEST(!(weak_comp(b, wb) || weak_comp(wb, b)));
    BOOST_TEST(weak_comp(wa, wb) || weak_comp(wb, wa));
    BOOST_TEST(weak_comp(wa, b) || weak_comp(b, wa));
  }

  return boost::report_errors();
}
void
SoIntersectionDetectionAction::apply(SoNode * node)
{
  // Keep this around, as it's handy for dumping a stand-alone scene
  // to work with from an invocation within an application framework.
#if 0 // disabled
  SoOutput out;
  SbBool ok = out.openFile("/tmp/assembly.wrl");
  assert(ok);
  SoWriteAction wa(&out);
  wa.apply(node);
  out.closeFile();
#endif // disabled

  PRIVATE(this)->reset();

  // Needs a bounding box for the full scene, for later initialization
  // of the SbOctTree of shape bounding boxes.
  SbViewportRegion vp;
  SoGetBoundingBoxAction bboxaction(vp);
  bboxaction.apply(node);
  PRIVATE(this)->fullxfbbox = bboxaction.getXfBoundingBox();

  if (ida_debug()) { // debug
    SoGetPrimitiveCountAction counter;
    counter.apply(node);
    SoDebugError::postInfo("SoIntersectionDetectionAction::apply",
                           "number of triangle primitives in scene: %d",
                           counter.getTriangleCount());
  }

  PRIVATE(this)->traverser->apply(node);

  SbTime starttime;
  if (ida_debug()) { // debug
    starttime = SbTime::getTimeOfDay();
    SoDebugError::postInfo("SoIntersectionDetectionAction::apply",
                           "calling doIntersectionTesting()...");
  }

  PRIVATE(this)->doIntersectionTesting();

  if (ida_debug()) { // debug
    SoDebugError::postInfo("SoIntersectionDetectionAction::apply",
                           "doIntersectionTesting() done after %f seconds.",
                           (SbTime::getTimeOfDay() - starttime).getValue());
  }
}
예제 #21
0
파일: SoNode.cpp 프로젝트: Alexpux/Coin3D
// Documentation in superclass.
void
SoNode::writeInstance(SoOutput * out)
{
  SoNode * node = this;

  SoProtoInstance * proto = SoProtoInstance::findProtoInstance(this);
  if (proto) { node = proto; }

  // Catch common misuse of SoOutput (a single pass instead of two,
  // lacking the setStage() initialization).
  assert(((out->getStage() == SoOutput::COUNT_REFS) ||
          (out->getStage() == SoOutput::WRITE)) &&
         "unknown write stage");
  SoWriteAction wa(out);
  wa.continueToApply(node);
}
예제 #22
0
void Reaching::ProjectVector(cart_vec_t& vcart,joint_vec_t& vangle, joint_vec_t& out){
    Matrix jac, 
        jact, m31,m32(cartesian_dim,cartesian_dim,false),
        wa(joint_angle_dim,joint_angle_dim,false); 
    joint_vec_t v41,v42;
    cart_vec_t v31,v32;
    body->Jacobian(pos_angle,jac); //J
    jact = jac.Transpose();
    wa.Diag(weight_angle);
    v31= vcart-jac*vangle;
    m31 = jac*wa*jact;
    m31 += m32.Diag(weight_cart);
    m32 = m31.Inverse();
    if(!Matrix::IsInverseOk()){cout<<"bad inversion"<<endl;}
    out = vangle+wa*jact*m32*v31;
}
예제 #23
0
파일: grader.c 프로젝트: blmarket/icpc
int check_element(char* x) {
    if (--r < 0 || !compiled || !check(x)) {
        wa();
    }
    struct node* current = set;
    for (int i = 0; i < n; i++) {
        if (x[i] == '0') {
            if (current->zero == 0) {
                return 0;
            }
            current = current->zero;
        }
        else {
            if (current->one == 0) {
                return 0;
            }
            current = current->one;
        }
    }
    return 1;
}
예제 #24
0
void TestString( const Allocator& aIn )
{
    // Strings are made of chars or wide chars
    typedef typename Allocator::template rebind< char >::other CharAlloc;
    typedef typename Allocator::template rebind< wchar_t >::other WCharAlloc;

    typedef std::basic_string< char,
                               std::char_traits< char >,
                               CharAlloc > String;
    typedef std::basic_string< wchar_t,
                               std::char_traits< wchar_t >,
                               WCharAlloc > WString;

    // string
    CharAlloc a( aIn );

    String s1( Policy< Allocator >::template GetDefault< String >( a ) );
    String s2( Policy< Allocator >::template GetCopied< String >( a ) );

    TestString( a, s1 );
    TestString( a, s2 );

    s1.swap( s2 );

    TestString( a, s1 );
    TestString( a, s2 );

    // wstring
    WCharAlloc wa( aIn );
    WString w1( Policy< Allocator >::template GetDefault< WString >( wa ) );
    WString w2( Policy< Allocator >::template GetCopied< WString >( wa ) );

    TestString( wa, w1 );
    TestString( wa, w2 );

    w1.swap( w2 );

    TestString( wa, w1 );
    TestString( wa, w2 );
}
osgDB::ReaderWriter::WriteResult
ReaderWriterIV::writeNode(const osg::Node& node, const std::string& fileName,
                          const osgDB::ReaderWriter::Options* /*options*/) const
{
    // accept extension
    std::string ext = osgDB::getLowerCaseFileExtension(fileName);
    if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
    bool useVRML1 = !isInventorExtension(osgDB::getFileExtension(fileName));

    OSG_NOTICE << "osgDB::ReaderWriterIV::writeNode() Writing file "
                             << fileName.data() << std::endl;

    // Convert OSG graph to Inventor graph
    ConvertToInventor osg2iv;
    osg2iv.setVRML1Conversion(useVRML1);
    (const_cast<osg::Node*>(&node))->accept(osg2iv);
    SoNode *ivRoot = osg2iv.getIvSceneGraph();
    if (ivRoot == NULL)
        return WriteResult::ERROR_IN_WRITING_FILE;
    ivRoot->ref();

    // Change prefix according to VRML spec:
    // Node names must not begin with a digit, and must not contain spaces or
    // control characters, single or double quote characters, backslashes, curly braces,
    // the sharp (#) character, the plus (+) character or the period character.
    if (useVRML1)
      SoBase::setInstancePrefix("_");

    // Write Inventor graph to file
    SoOutput out;
    out.setHeaderString((useVRML1) ? "#VRML V1.0 ascii" : "#Inventor V2.1 ascii");
    if (!out.openFile(fileName.c_str()))
        return WriteResult::ERROR_IN_WRITING_FILE;
    SoWriteAction wa(&out);
    wa.apply(ivRoot);
    ivRoot->unref();

    return WriteResult::FILE_SAVED;
}
예제 #26
0
파일: SoSFNode.cpp 프로젝트: Alexpux/Coin3D
// Overridden from parent to propagate write reference counting to
// node.
void
SoSFNode::countWriteRefs(SoOutput * out) const
{
  inherited::countWriteRefs(out);

  SoBase * base = this->getValue();
  if (base == NULL) return;

  // NB: This code is common for SoSFNode, SoSFPath and SoSFEngine.
  // That's why we check the base type before writing/counting

  if (base->isOfType(SoNode::getClassTypeId())) {
    coin_assert_cast<SoNode *>(base)->writeInstance(out);
  }
  else if (base->isOfType(SoEngine::getClassTypeId())) {
    coin_assert_cast<SoEngine *>(base)->addWriteReference(out);
  }
  else if (base->isOfType(SoPath::getClassTypeId())) {
    SoWriteAction wa(out);
    wa.continueToApply(coin_assert_cast<SoPath *>(base));
  }
}
예제 #27
0
bool CoinVisualizationNode::saveModel(const std::string &modelPath, const std::string &filename)
{
	std::string outFile = filename;

	boost::filesystem::path completePath(modelPath);
	boost::filesystem::path fn(outFile);

	if (!boost::filesystem::is_directory(completePath))
	{
		if (!boost::filesystem::create_directories(completePath))
		{
			VR_ERROR << "Could not create model dir  " << completePath.string() << endl;
			return false;
		}
	}

	boost::filesystem::path completeFile = boost::filesystem::operator/(completePath,fn);

    SoOutput* so = new SoOutput();
    if (!so->openFile(completeFile.string().c_str()))
    {
        VR_ERROR << "Could not open file " << completeFile.string() << " for writing." << endl;
    }
	SoGroup *n = new SoGroup;
	n->ref();
	n->addChild(visualization);
	SoGroup* newVisu = CoinVisualizationFactory::convertSoFileChildren(n);
	newVisu->ref();
    SoWriteAction wa(so);
    wa.apply(newVisu);
	so->closeFile();

	newVisu->unref();
	n->unref();

    return true;
}
    Disposable<std::vector<Size> > qrDecomposition(const Matrix& M,
                                                   Matrix& q, Matrix& r,
                                                   bool pivot) {
        Matrix mT = transpose(M);
        const Size m = M.rows();
        const Size n = M.columns();

        boost::scoped_array<int> lipvt(new int[n]);
        boost::scoped_array<Real> rdiag(new Real[n]);
        boost::scoped_array<Real> wa(new Real[n]);

        MINPACK::qrfac(m, n, mT.begin(), 0, (pivot)?1:0,
                       lipvt.get(), n, rdiag.get(), rdiag.get(), wa.get());
        if (r.columns() != n || r.rows() !=n)
            r = Matrix(n, n);

        for (Size i=0; i < n; ++i) {
            std::fill(r.row_begin(i), r.row_begin(i)+i, 0.0);
            r[i][i] = rdiag[i];
            if (i < m) {
                std::copy(mT.column_begin(i)+i+1, mT.column_end(i),
                          r.row_begin(i)+i+1);
            }
            else {
                std::fill(r.row_begin(i)+i+1, r.row_end(i), 0.0);
            }
        }

        if (q.rows() != m || q.columns() != n)
            q = Matrix(m, n);

        if (m > n) {
            std::fill(q.begin(), q.end(), 0.0);

            Integer u = std::min(n,m);
            for (Size i=0; i < u; ++i)
                q[i][i] = 1.0;

            Array v(m);
            for (Integer i=u-1; i >=0; --i) {
                if (std::fabs(mT[i][i]) > QL_EPSILON) {
                    const Real tau = 1.0/mT[i][i];

                    std::fill(v.begin(), v.begin()+i, 0.0);
                    std::copy(mT.row_begin(i)+i, mT.row_end(i), v.begin()+i);

                    Array w(n, 0.0);
                    for (Size l=0; l < n; ++l)
                        w[l] += std::inner_product(
                            v.begin()+i, v.end(), q.column_begin(l)+i, 0.0);

                    for (Size k=i; k < m; ++k) {
                        const Real a = tau*v[k];
                        for (Size l=0; l < n; ++l)
                            q[k][l] -= a*w[l];
                    }
                }
            }
        }
        else {
            Array w(m);
            for (Size k=0; k < m; ++k) {
                std::fill(w.begin(), w.end(), 0.0);
                w[k] = 1.0;

                for (Size j=0; j < std::min(n, m); ++j) {
                    const Real t3 = mT[j][j];
                    if (t3 != 0.0) {
                        const Real t
                            = std::inner_product(mT.row_begin(j)+j, mT.row_end(j),
                                                 w.begin()+j, 0.0)/t3;
                        for (Size i=j; i<m; ++i) {
                            w[i]-=mT[j][i]*t;
                        }
                    }
                    q[k][j] = w[j];
                }
                std::fill(q.row_begin(k) + std::min(n, m), q.row_end(k), 0.0);
            }
        }

        std::vector<Size> ipvt(n);

        if (pivot) {
            std::copy(lipvt.get(), lipvt.get()+n, ipvt.begin());
        }
        else {
            for (Size i=0; i < n; ++i)
                ipvt[i] = i;
        }

        return ipvt;
    }
예제 #29
0
파일: grader.c 프로젝트: blmarket/icpc
void add_element(char* x) {
    if (--w < 0 || compiled || !check(x)) {
        wa();
    }
    add_impl(set, x, 0);
}
예제 #30
0
bool DiacriticRules::on_match()
{
    double ambiguity_reduction = 0.0;
    int least_ambiguity_position = -1;

    /** Number of Morphemes **/
    int number_of_morphemes = 0;

    /** letter count of unvocalized word **/
    int length = 0;

    QString vocalizedWord;
    QString unvocalizedWord;
    QVector<QString> prefixPOSs;
    QVector<QString> prefixes;
    QString stemPOS;
    QVector<QString> suffixPOSs;
    QVector<QString> suffixes;

    int prefix_length = 0;
    /** letter count of stem **/
    int stem_length = 0;
    int suffix_length = 0;

    /** Get vocalized and unvocalized words **/
    int prefix_infos_size = prefix_infos->size();
    for (int i= 0; i<prefix_infos_size;i++) {
        minimal_item_info & pre = (*prefix_infos)[i];
        if(!(pre.raw_data.isEmpty())) {
            number_of_morphemes++;
            vocalizedWord.append(pre.raw_data);
        }
    }
    prefix_length = removeDiacritics(vocalizedWord).count();

    number_of_morphemes++;
    vocalizedWord.append(stem_info->raw_data);
    stem_length = removeDiacritics(stem_info->raw_data).count();

    int suffix_infos_size = suffix_infos->size();
    for (int i=0;i<suffix_infos_size;i++) {
        minimal_item_info & suff = (*suffix_infos)[i];
        if(!(suff.raw_data.isEmpty())) {
            number_of_morphemes++;
            vocalizedWord.append(suff.raw_data);
        }
    }

    unvocalizedWord = removeDiacritics(vocalizedWord);

    /** Unvocalized word Character Count **/
    length = unvocalizedWord.count();
    suffix_length = length - (prefix_length + stem_length);

    /** Ambiguity of the unvocalized word **/
    int unvocalizedAmbiguity = 0;
    WordAmbiguity wa(&unvocalizedWord, &unvocalizedAmbiguity);
    wa();

    /** Discard this morphological solution if the unvocalized word is not ambiguous (has 1 morpho. solution) **/
    if(unvocalizedAmbiguity < 2) {
        return true;
    }

    /// Select required morphological features

    /** Prefix Features **/
    int j = 0;
    for (int i = (prefix_infos_size-1); (i>=0) && (j<4);i--) {
        minimal_item_info & pre = (*prefix_infos)[i];
        if(pre.POS.isEmpty() && pre.raw_data.isEmpty()) {
            continue;
        }

        QStringList pre_poss = pre.POS.split('/');
        if(pre_poss.count() != 2) {
            continue;
        }
        QString unvoc_pre_data = removeDiacritics(pre.raw_data);
        if(!(unvoc_pre_data.isEmpty())) {
            prefixes.prepend(unvoc_pre_data);
        }
        if(!(pre_poss[1].isEmpty())) {
            prefixPOSs.prepend(pre_poss[1]);
        }
        j++;
    }

    while(prefixes.count() < 4) {
        prefixes.prepend("EPRE");
    }

    while(prefixPOSs.count() < 4) {
        prefixPOSs.prepend("EPREPOS");
    }

    /** Stem Features **/
    minimal_item_info & stem = *stem_info;
    //stem_length = removeDiacritics(stem.raw_data).count();
    QStringList stem_poss = stem.POS.split('/');
    if(stem_poss.count() != 2) {
        return true;
    }
    stemPOS = stem_poss[1];

    /** Suffix Features **/
    j = 0;
    for (int i=0;(i<suffix_infos_size) && (j<4);i++) {
        minimal_item_info & suff = (*suffix_infos)[i];
        if(suff.POS.isEmpty() && suff.raw_data.isEmpty()) {
            continue;
        }

        QStringList suff_poss = suff.POS.split('/');
        if(suff_poss.count() != 2) {
            continue;
        }
        QString unvoc_suf_data = removeDiacritics(suff.raw_data);
        if(!(unvoc_suf_data.isEmpty())) {
            suffixes.append(unvoc_suf_data);
        }
        if(!(suff_poss[1].isEmpty())) {
            suffixPOSs.append(suff_poss[1]);
        }
        j++;
    }

    while(suffixes.count() < 4) {
        suffixes.append("ESUF");
    }

    while(suffixPOSs.count() < 4) {
        suffixPOSs.append("ESUFPOS");
    }

    /// Detach diacritics from raw_data and store in separate structure
    int diacritic_Counter = 0;
    QVector<QVector<QChar> > wordDiacritics(length);
    int letterIndex = 0;
    for(int i=1; i<vocalizedWord.count(); i++) {
        QChar currentLetter= vocalizedWord[i];
        if(isDiacritic(currentLetter)) {
            wordDiacritics[letterIndex].append(currentLetter);
            diacritic_Counter++;
        }
        else {
            letterIndex++;
        }
    }

    if(diacritic_Counter == 0) {
        return true;
    }

    /// Get the number of solutions for each solution with one diacritic
    /// Select diacritic position leastambiguous = least number of morphological solutions
    QVector<QVector<int> > diacriticAmbiguity(length);
    int least_ambiguity = unvocalizedAmbiguity + 1;
    int diacritic_Index = -1;
    for(int i=0; i< wordDiacritics.count(); i++) {
        for(j=0; j< wordDiacritics.at(i).count(); j++) {
            QString one_diacritic_word = unvocalizedWord;
            one_diacritic_word.insert(i+1,wordDiacritics[i][j]);

            int one_diacritic_Ambiguity = 0;
            WordAmbiguity wa(&one_diacritic_word, &one_diacritic_Ambiguity);
            wa();

            if(one_diacritic_Ambiguity == 0) {
                diacriticAmbiguity[i].append(unvocalizedAmbiguity);
            }
            else {
                diacriticAmbiguity[i].append(one_diacritic_Ambiguity);
            }

            if(diacriticAmbiguity[i][j] <  least_ambiguity) {
                least_ambiguity = diacriticAmbiguity[i][j];
                least_ambiguity_position = i;
                diacritic_Index = j;
            }
        }
    }

    /** This weirdly happens when a word partial diacritics has ambiguity more than the unvocalized word (ex. dAn) **/
    if((least_ambiguity_position == -1) || (diacritic_Index == -1)) {
        if(number_of_solutions == -1) {
            return true;
        }
        else if(solution_counter != number_of_solutions) {
            solution_counter++;
            return true;
        }
        else {
            return false;
        }
    }

    ambiguity_reduction = ((unvocalizedAmbiguity- diacriticAmbiguity[least_ambiguity_position][diacritic_Index]) * 1.0) / unvocalizedAmbiguity;

    /** Filter data to extract high ambiguity reduction instances **/

    if(ambiguity_reduction < 0.667) {
        if(number_of_solutions == -1) {
            return true;
        }
        else if(solution_counter != number_of_solutions) {
            solution_counter++;
            return true;
        }
        else {
            return false;
        }
    }
    filtered_items++;

    /** Print/Use data **/

    theSarf->out << number_of_morphemes << "  "
            << length << "  "
            << stem_length << "  ";

    //    prefixPOSs
    for(int i=0; i<prefixPOSs.count(); i++) {
        theSarf->out << prefixPOSs[i] << "  ";
    }

    //    prefixes
    for(int i=0; i< prefixes.count(); i++) {
        theSarf->out << prefixes[i] << "  ";
    }

    //    stemPOS
    theSarf->out << stemPOS << "  ";

    //    suffixPOSs
    for(int i=0; i<suffixPOSs.count(); i++) {
        theSarf->out << suffixPOSs[i] << "  ";
    }

    //    suffixes
    for(int i=0; i<suffixes.count(); i++) {
        theSarf->out << suffixes[i] << "  ";
    }

    //    least_ambiguity_position
    //    prefixs , prefixm, prefixe , stems , stemm, steme , suffixs , suffixm, suffixe
    //theSarf->out << least_ambiguity_position << "  ";
    QString diacritic_position;

    if((prefix_length != 0) && (least_ambiguity_position == 0)) {
        diacritic_position = "prefixs";
    }
    else if((prefix_length != 0) && (least_ambiguity_position > 0) && (least_ambiguity_position < (prefix_length-1))) {
        diacritic_position = "prefixm";
    }
    else if((prefix_length != 0) && (least_ambiguity_position == (prefix_length-1))) {
        diacritic_position = "prefixe";
    }
    else if(least_ambiguity_position == prefix_length) {
        diacritic_position = "stems";
    }
    else if((least_ambiguity_position > (prefix_length)) && (least_ambiguity_position < (prefix_length + stem_length - 1))) {
        diacritic_position = "stemm";
    }
    else if(least_ambiguity_position == (prefix_length + stem_length - 1)) {
        diacritic_position = "steme";
    }
    else if((suffix_length != 0) && (least_ambiguity_position == (prefix_length + stem_length))) {
        diacritic_position = "suffixs";
    }
    else if((suffix_length != 0) && (least_ambiguity_position > (prefix_length + stem_length)) && (least_ambiguity_position < (length - 1))) {
        diacritic_position = "suffixm";
    }
    else if((suffix_length != 0) && (least_ambiguity_position == (length -1))) {
        diacritic_position = "suffixe";
    }
    else {
        cout << "Couldn't set diacritic position!" << endl;
        return false;
    }
    theSarf->out << diacritic_position << '\n';

    //    ambiguity_reduction
    //theSarf->out << ambiguity_reduction << '\n';

    /** Check for number of solutions requested **/
    if(number_of_solutions == -1) {
        return true;
    }
    else if(solution_counter != number_of_solutions) {
        solution_counter++;
        return true;
    }
    else {
        return false;
    }
};