예제 #1
0
    void bvisit(const Mul &x)
    {

        RCP<const Basic> curr_num = one;
        RCP<const Basic> curr_den = one;
        RCP<const Basic> arg_num, arg_den, t;

        for (const auto &arg : x.get_args()) {
            as_numer_denom(arg, outArg(arg_num), outArg(arg_den));
            // TODO: This is naive and slow. Fix it
            t = div(curr_num, arg_den);
            if (neq(*t, x)) {
                as_numer_denom(t, outArg(curr_num), outArg(arg_den));
            }
            t = div(curr_den, arg_num);
            if (neq(*t, x)) {
                as_numer_denom(t, outArg(curr_den), outArg(arg_num));
            }
            curr_num = mul(curr_num, arg_num);
            curr_den = mul(curr_den, arg_den);
        }

        *numer_ = curr_num;
        *denom_ = curr_den;
    }
예제 #2
0
int main()
{
  if (nge(INT_MIN, INT_MAX) !=  0) abort();
  if (nge(INT_MAX, INT_MIN) != -1) abort();
  if (ngt(INT_MIN, INT_MAX) !=  0) abort();
  if (ngt(INT_MAX, INT_MIN) != -1) abort();
  if (nle(INT_MIN, INT_MAX) != -1) abort();
  if (nle(INT_MAX, INT_MIN) !=  0) abort();
  if (nlt(INT_MIN, INT_MAX) != -1) abort();
  if (nlt(INT_MAX, INT_MIN) !=  0) abort();

  if (neq(INT_MIN, INT_MAX) !=  0) abort();
  if (neq(INT_MAX, INT_MIN) !=  0) abort();
  if (nne(INT_MIN, INT_MAX) != -1) abort();
  if (nne(INT_MAX, INT_MIN) != -1) abort();

  if (ngeu(0, ~0U) !=  0) abort();
  if (ngeu(~0U, 0) != -1) abort();
  if (ngtu(0, ~0U) !=  0) abort();
  if (ngtu(~0U, 0) != -1) abort();
  if (nleu(0, ~0U) != -1) abort();
  if (nleu(~0U, 0) !=  0) abort();
  if (nltu(0, ~0U) != -1) abort();
  if (nltu(~0U, 0) !=  0) abort();
  
  exit(0);
}
예제 #3
0
void ReactorNet::initialize()
{
    size_t n, nv;
    char buf[100];
    m_nv = 0;
    writelog("Initializing reactor network.\n", m_verbose);
    if (m_reactors.empty())
        throw CanteraError("ReactorNet::initialize",
                           "no reactors in network!");
    size_t sensParamNumber = 0;
    m_start.assign(1, 0);
    for (n = 0; n < m_reactors.size(); n++) {
        Reactor& r = *m_reactors[n];
        r.initialize(m_time);
        nv = r.neq();
        m_nparams.push_back(r.nSensParams());
        std::vector<std::pair<void*, int> > sens_objs = r.getSensitivityOrder();
        for (size_t i = 0; i < sens_objs.size(); i++) {
            std::map<size_t, size_t>& s = m_sensOrder[sens_objs[i]];
            for (std::map<size_t, size_t>::iterator iter = s.begin();
                    iter != s.end();
                    ++iter) {
                m_sensIndex.resize(std::max(iter->second + 1, m_sensIndex.size()));
                m_sensIndex[iter->second] = sensParamNumber++;
            }
        }
        m_nv += nv;
        m_start.push_back(m_nv);

        if (m_verbose) {
            sprintf(buf,"Reactor %s: %s variables.\n",
                    int2str(n).c_str(), int2str(nv).c_str());
            writelog(buf);
            sprintf(buf,"            %s sensitivity params.\n",
                    int2str(r.nSensParams()).c_str());
            writelog(buf);
        }
        if (r.type() == FlowReactorType && m_reactors.size() > 1) {
            throw CanteraError("ReactorNet::initialize",
                               "FlowReactors must be used alone.");
        }
    }

    m_ydot.resize(m_nv,0.0);
    m_atol.resize(neq());
    fill(m_atol.begin(), m_atol.end(), m_atols);
    m_integ->setTolerances(m_rtol, neq(), DATA_PTR(m_atol));
    m_integ->setSensitivityTolerances(m_rtolsens, m_atolsens);
    m_integ->setMaxStepSize(m_maxstep);
    m_integ->setMaxErrTestFails(m_maxErrTestFails);
    if (m_verbose) {
        sprintf(buf, "Number of equations: %s\n", int2str(neq()).c_str());
        writelog(buf);
        sprintf(buf, "Maximum time step:   %14.6g\n", m_maxstep);
        writelog(buf);
    }
    m_integ->initialize(m_time, *this);
    m_integrator_init = true;
    m_init = true;
}
예제 #4
0
void testPtrs(void)
{
#ifndef __SDCC_pic16
#if defined (__SDCC_MODEL_HUGE)
	char __code  * cp2 = (char __code *)0x0002;
	void (* fp2)(void) = (void (*)(void))0x0002;

	ASSERT (eq(cp2, fp2));
	ASSERT (smaller(fpE, fpF));
#endif

	ASSERT (xp0 == NULL);
	ASSERT (ip0 == NULL);
	ASSERT (pp0 == NULL);
	ASSERT (cp0 == NULL);
	ASSERT (fp0 == NULL);
	ASSERT (gp0 == NULL);

	ASSERT (xp1 != NULL);
	ASSERT (ip1 != NULL);
	ASSERT (pp1 != NULL);
	ASSERT (cp1 != NULL);
	ASSERT (fp1 != NULL);
	ASSERT (gp2 != NULL);

	ASSERT (eq(xp0, ip0));
	ASSERT (eq(xp0, pp0));
	ASSERT (eq(xp0, cp0));
	ASSERT (eq(xp0, fp0));
	ASSERT (eq(xp0, gp0));

#if defined(__SDCC_mcs51) || defined(__SDCC_ds390)
	ASSERT (neq(xp1, ip1));
	ASSERT (neq(xp1, pp1));
	ASSERT (neq(xp1, cp1));
	ASSERT (neq(xp1, fp1));
	ASSERT (neq(xp1, gp2));

	ASSERT (smaller(xp1, ip1) || greater(xp1, ip1));
	ASSERT (smaller(xp1, pp1) || greater(xp1, pp1));
	ASSERT (smaller(xp1, cp1) || greater(xp1, cp1));
	ASSERT (smaller(xp1, fp1) || greater(xp1, fp1));
	ASSERT (smaller(xp1, gp2) || greater(xp1, gp2));

	ASSERT (!smaller(xp0, ip0) && !greater(xp0, ip0));
	ASSERT (!smaller(xp0, pp0) && !greater(xp0, pp0));
	ASSERT (!smaller(xp0, cp0) && !greater(xp0, cp0));
	ASSERT (!smaller(xp0, fp0) && !greater(xp0, fp0));
	ASSERT (!smaller(xp0, gp0) && !greater(xp0, gp0));
#endif

	ASSERT (eq(cp1, fp1));
	ASSERT (smaller(pp1, gp2));
#endif
}
예제 #5
0
RCP<const Set> Interval::set_intersection(const RCP<const Set> &o) const
{
    if (is_a<Interval>(*o)) {
        const Interval &other = static_cast<const Interval &>(*o);
        RCP<const Number> start, end;
        bool left_open, right_open;
        RCP<const Basic> start_end, end_start;
        start_end = min({this->start_, other.end_});
        end_start = min({this->end_, other.start_});

        if (eq(*this->start_, *start_end) and eq(*other.start_, *end_start)) {
            RCP<const Basic> start_start, end_end;
            start_start = min({this->start_, other.start_});
            end_end = min({this->end_, other.end_});
            if (neq(*this->start_, *other.start_)) {
                if (eq(*this->start_, *start_start)) {
                    start = other.start_;
                    left_open = other.left_open_;
                } else {
                    start = this->start_;
                    left_open = this->left_open_;
                }
            } else {
                start = this->start_;
                left_open = this->left_open_ or other.left_open_;
            }

            if (neq(*this->end_, *other.end_)) {
                if (eq(*this->end_, *end_end)) {
                    end = this->end_;
                    right_open = this->right_open_;
                } else {
                    end = other.end_;
                    right_open = other.right_open_;
                }
            } else {
                end = this->end_;
                right_open = this->right_open_ or other.right_open_;
            }
            return interval(start, end, left_open, right_open);
        } else {
            return emptyset();
        }
    }
    if (is_a<UniversalSet>(*o) or is_a<EmptySet>(*o) or is_a<FiniteSet>(*o)
        or is_a<Union>(*o)) {
        return (*o).set_intersection(rcp_from_this_cast<const Set>());
    }
    throw std::runtime_error("Not implemented");
}
예제 #6
0
파일: mul.cpp 프로젝트: MridulS/csympy
std::string Mul::__str__() const
{
    std::ostringstream o;
    if (eq(coef_, minus_one)) {
        o << "-";
    } else if (is_a<Rational>(*coef_) &&
                !(rcp_static_cast<const Rational>(coef_)->is_int())) {
        o << "(" << *coef_ <<")";
    } else if (is_a<Complex>(*coef_)) {
        if (!(rcp_static_cast<const Complex>(coef_)->is_reim_zero())) {
            o << "(" << *coef_ <<")";
        } else {
            o << *coef_;
        }
    } else if (neq(coef_, one)) {
        o << *coef_;
    }

    auto p = dict_.begin();
    if (neq(coef_, minus_one) && neq(coef_, one)) o << "*";
    for (; p != dict_.end(); p++) {
        if (is_a<Add>(*(p->first))) {
            o << "(" << *(p->first) << ")";
        } else if (is_a<Rational>(*(p->first)) &&
                !(rcp_static_cast<const Rational>((p->first))->is_int())) {
            o << "(" << *(p->first) <<")";
        } else if (is_a<Complex>(*(p->first))) {
            if (!(rcp_static_cast<const Complex>((p->first))->is_reim_zero())) {
                o << "(" << *(p->first) <<")";
            } else {
                o << *(p->first);
            }
        } else {
            o << *(p->first);
        }
        if (neq(p->second, one)) {
            o << "^";
            if (!is_a<Integer>(*(p->second)) && !is_a<Symbol>(*(p->second)))
                o << "(";
            o << *(p->second);
            if (!is_a<Integer>(*(p->second)) && !is_a<Symbol>(*(p->second)))
                o << ")";
        }
        o << "*";
    }

    std::string s = o.str();
    return s.substr(0, s.size()-1);
}
void UmlExtraClassMember::add_init(UmlClass * cl, WrapperStr def, bool roundtrip,
                                   QList<UmlItem *> & expected_order)
{
    if (roundtrip) {
        const QVector<UmlItem*> & ch = cl->children();
        UmlItem *const* v = ch.data();
        UmlItem *const*  vsup = v + ch.size();
        UmlItem * x;

        for (; v != vsup; v += 1) {
            if (((x = *v)->kind() == anExtraClassMember) &&
                ((UmlExtraClassMember *) x)->is_useless() &&
                (x->name() == "initialization")) {
                expected_order.append(x);

                if (neq(((UmlExtraClassMember *) x)->javaDecl(), def)) {
                    ((UmlExtraClassMember *) x)->set_JavaDecl(def);
                    cl->get_class()->set_updated();
                }

                ((UmlExtraClassMember *) x)->set_usefull();
                return;
            }
        }
    }

    UmlExtraClassMember * x =
        UmlExtraClassMember::create(cl, "initialization");

    x->set_JavaDecl(def);
    expected_order.append(x);
}
예제 #8
0
void StrPrinter::bvisit(const Add &x) {
    std::ostringstream o;
    bool first = true;
    std::map<RCP<const Basic>, RCP<const Number>,
            RCPBasicKeyLessCmp> dict(x.dict_.begin(), x.dict_.end());

    if (neq(*(x.coef_), *zero)) {
        o << this->apply(x.coef_);
        first = false;
    }
    for (auto &p: dict) {
        std::string t;
        if (eq(*(p.second), *one)) {
            t = this->apply(p.first);
        } else if(eq(*(p.second), *minus_one)) {
            t = "-" + parenthesizeLT(p.first, PrecedenceEnum::Mul);
        } else {
            t = parenthesizeLT(p.second, PrecedenceEnum::Mul) + "*" + parenthesizeLT(p.first, PrecedenceEnum::Mul);
        }

        if (!first) {
            if (t[0] == '-') {
                o << " - " << t.substr(1);
            } else {
                o << " + " << t;
            }
        } else {
            o << t;
            first = false;
        }
    }
    str_ = o.str();
}
예제 #9
0
bool CSRMatrix::eq(const MatrixBase &other) const
{
    unsigned row = this->nrows();
    if (row != other.nrows() or this->ncols() != other.ncols())
        return false;

    if (is_a<CSRMatrix>(other)) {
        const CSRMatrix &o = down_cast<const CSRMatrix &>(other);

        if (this->p_[row] != o.p_[row])
            return false;

        for (unsigned i = 0; i <= row; i++)
            if (this->p_[i] != o.p_[i])
                return false;

        for (unsigned i = 0; i < this->p_[row]; i++)
            if ((this->j_[i] != o.j_[i]) or neq(*this->x_[i], *(o.x_[i])))
                return false;

        return true;
    } else {
        return this->MatrixBase::eq(other);
    }
}
예제 #10
0
void StrPrinter::bvisit(const Mul &x) {
    std::ostringstream o, o2;
    bool num = false;
    unsigned den = 0;
    std::map<RCP<const Basic>, RCP<const Basic>,
            RCPBasicKeyLessCmp> dict(x.dict_.begin(), x.dict_.end());

    if (eq(*(x.coef_), *minus_one)) {
        o << "-";
    } else if (neq(*(x.coef_), *one)) {
        o << parenthesizeLT(x.coef_, PrecedenceEnum::Mul) << "*";
        num = true;
    }

    for (auto &p: dict) {
        if ((is_a<Integer>(*p.second) &&
             rcp_static_cast<const Integer>(p.second)->is_negative()) ||
            (is_a<Rational>(*p.second) &&
             rcp_static_cast<const Rational>(p.second)->is_negative())) {
            if(eq(*(p.second), *minus_one)) {
                o2 << parenthesizeLT(p.first, PrecedenceEnum::Mul);
            } else {
                o2 << parenthesizeLE(p.first, PrecedenceEnum::Pow);
                o2 << "**";
                o2 << parenthesizeLE(neg(p.second), PrecedenceEnum::Pow);
            }
            o2 << "*";
            den++;
        } else {
            if(eq(*(p.second), *one)) {
                o << parenthesizeLT(p.first, PrecedenceEnum::Mul);
            } else {
                o << parenthesizeLE(p.first, PrecedenceEnum::Pow);
                o << "**";
                o << parenthesizeLE(p.second, PrecedenceEnum::Pow);
            }
            o << "*";
            num = true;
        }
    }

    if (!num) {
        o << "1*";
    }

    std::string s = o.str();
    s = s.substr(0, s.size() - 1);

    if (den != 0) {
        std::string s2 = o2.str();
        s2 = s2.substr(0, s2.size() - 1);
        if (den > 1) {
            str_ = s + "/(" + s2 + ")";
        } else {
            str_ = s + "/" + s2;
        }
    } else {
        str_ = s;
    }
}
예제 #11
0
unsigned pivot(DenseMatrix &B, unsigned r, unsigned c)
{
    unsigned k = r;

    if (eq(*(B.m_[r * B.col_ + c]), *zero))
        for (k = r; k < B.row_; k++)
            if (neq(*(B.m_[k * B.col_ + c]), *zero))
                break;
    return k;
}
예제 #12
0
파일: dict.cpp 프로젝트: achabill/symengine
bool vec_basic_eq(const vec_basic &a, const vec_basic &b)
{
    // Can't be equal if # of entries differ:
    if (a.size() != b.size()) return false;
    // Loop over elements in "a" and "b":
    for (size_t i = 0; i < a.size(); i++) {
        if (neq(*a[i], *b[i])) return false; // values not equal
    }
    return true;
}
예제 #13
0
int check(int size, float *dataOut, float *expectedOut)
{
  int status = 0;
  for (int i = 0; i < size ; i++) {
    if (neq(dataOut[i],expectedOut[i])) {
      //fprintf(stderr, "Error in output data at location %d, expected %g, received %g\n",i, expectedOut[i], dataOut[i]);
      status = 1;
    }
  }
  return status;
}
예제 #14
0
파일: add.cpp 프로젝트: MridulS/csympy
std::string Add::__str__() const
{
    std::ostringstream o;
    if (neq(coef_, zero))
        o << *coef_ << " + ";
    int counter = 0;
    for (auto &p: dict_) {
        if (eq(p.second, one))
            o << *(p.first);
        else {
            // TODO: extend this for Rationals as well:
            if (is_a<Integer>(*p.second) &&
                    rcp_static_cast<const Integer>(p.second)->is_negative()
                    && o.tellp() >= 3)
                o.seekp(-3, std::ios_base::cur);
            if (eq(p.second, minus_one)) {
                if (counter >= 1)
                    o << " - ";
                else
                    o << "-";
            } else {
                // TODO: extend this for Rationals as well:
                if (is_a<Integer>(*p.second) &&
                        rcp_static_cast<const Integer>(p.second)->is_negative()) {
                    if (counter >= 1) {
                        o << " - ";
                    } else {
                        o << "-";
                    }
                    o << -(rcp_static_cast<const Integer>(p.second))->i;
                } else if (is_a<Complex>(*p.second)) {
                    if (!(rcp_static_cast<const Complex>(p.second)->is_reim_zero())) {
                        o << "(" << *(p.second) <<")";
                    } else {
                        o << *(p.second);
                    }
                } else {
                    o << *(p.second);
                }
            }
            if (!eq(p.second, minus_one)) o << "*";
            if (is_a<Add>(*p.first) || is_a<Rational>(*p.first) || is_a<Complex>(*p.first)) {
                o << "(";
            }
            o << *(p.first);
            if (is_a<Add>(*p.first) || is_a<Rational>(*p.first) || is_a<Complex>(*p.first)) o << ")";
        }
        o << " + ";
        counter++;
    }
    o.seekp(-3, std::ios_base::cur);
    std::string s = o.str();
    return s.substr(0, o.tellp());
}
예제 #15
0
void ReactorNet::initialize()
{
    m_nv = 0;
    debuglog("Initializing reactor network.\n", m_verbose);
    if (m_reactors.empty()) {
        throw CanteraError("ReactorNet::initialize",
                           "no reactors in network!");
    }
    m_start.assign(1, 0);
    for (size_t n = 0; n < m_reactors.size(); n++) {
        Reactor& r = *m_reactors[n];
        r.initialize(m_time);
        size_t nv = r.neq();
        m_nv += nv;
        m_start.push_back(m_nv);

        if (m_verbose) {
            writelog("Reactor {:d}: {:d} variables.\n", n, nv);
            writelog("              {:d} sensitivity params.\n", r.nSensParams());
        }
        if (r.type() == FlowReactorType && m_reactors.size() > 1) {
            throw CanteraError("ReactorNet::initialize",
                               "FlowReactors must be used alone.");
        }
    }

    m_ydot.resize(m_nv,0.0);
    m_atol.resize(neq());
    fill(m_atol.begin(), m_atol.end(), m_atols);
    m_integ->setTolerances(m_rtol, neq(), m_atol.data());
    m_integ->setSensitivityTolerances(m_rtolsens, m_atolsens);
    m_integ->setMaxStepSize(m_maxstep);
    m_integ->setMaxErrTestFails(m_maxErrTestFails);
    if (m_verbose) {
        writelog("Number of equations: {:d}\n", neq());
        writelog("Maximum time step:   {:14.6g}\n", m_maxstep);
    }
    m_integ->initialize(m_time, *this);
    m_integrator_init = true;
    m_init = true;
}
예제 #16
0
파일: dict.cpp 프로젝트: achabill/symengine
bool set_eq(const T &A, const T &B)
{
    // Can't be equal if # of entries differ:
    if (A.size() != B.size()) return false;
    // Loop over elements in "a" and "b":
    auto a = A.begin();
    auto b = B.begin();
    for (; a != A.end(); ++a, ++b) {
        if (neq(**a, **b)) return false; // values not equal
    }
    return true;
}
예제 #17
0
파일: matrix.cpp 프로젝트: MridulS/csympy
bool MatrixBase::eq(const MatrixBase &other) const
{
	if (this->nrows() != other.nrows() || this->ncols() != other.ncols())
        return false;

    for (unsigned i = 0; i < this->nrows(); i++)
        for (unsigned j = 0; j < this->ncols(); j++)
        if(neq(this->get(i, j), other.get(i, j)))
            return false;

    return true;
}
예제 #18
0
// Pass 2 computes CSR entries for matrix C = A*B using the
// row pointer Cp[] computed in Pass 1.
void csr_matmat_pass2(const CSRMatrix &A, const CSRMatrix &B, CSRMatrix &C)
{
    std::vector<int> next(A.col_, -1);
    vec_basic sums(A.col_, zero);

    unsigned nnz = 0;

    C.p_[0] = 0;

    for (unsigned i = 0; i < A.row_; i++) {
        int head = -2;
        unsigned length = 0;

        unsigned jj_start = A.p_[i];
        unsigned jj_end = A.p_[i + 1];
        for (unsigned jj = jj_start; jj < jj_end; jj++) {
            unsigned j = A.j_[jj];
            RCP<const Basic> v = A.x_[jj];

            unsigned kk_start = B.p_[j];
            unsigned kk_end = B.p_[j + 1];
            for (unsigned kk = kk_start; kk < kk_end; kk++) {
                unsigned k = B.j_[kk];

                sums[k] = add(sums[k], mul(v, B.x_[kk]));

                if (next[k] == -1) {
                    next[k] = head;
                    head = k;
                    length++;
                }
            }
        }

        for (unsigned jj = 0; jj < length; jj++) {

            if (neq(*sums[head], *zero)) {
                C.j_[nnz] = head;
                C.x_[nnz] = sums[head];
                nnz++;
            }

            unsigned temp = head;
            head = next[head];

            next[temp] = -1; // clear arrays
            sums[temp] = zero;
        }

        C.p_[i + 1] = nnz;
    }
}
예제 #19
0
// ----------------------------- Determinant ---------------------------------//
RCP<const Basic> det_bareis(const DenseMatrix &A)
{
    SYMENGINE_ASSERT(A.row_ == A.col_);

    unsigned n = A.row_;

    if (n == 1) {
        return A.m_[0];
    } else if (n == 2) {
        // If A = [[a, b], [c, d]] then det(A) = ad - bc
        return sub(mul(A.m_[0], A.m_[3]), mul(A.m_[1], A.m_[2]));
    } else if (n == 3) {
        // if A = [[a, b, c], [d, e, f], [g, h, i]] then
        // det(A) = (aei + bfg + cdh) - (ceg + bdi + afh)
        return sub(add(add(mul(mul(A.m_[0], A.m_[4]), A.m_[8]),
                           mul(mul(A.m_[1], A.m_[5]), A.m_[6])),
                       mul(mul(A.m_[2], A.m_[3]), A.m_[7])),
                   add(add(mul(mul(A.m_[2], A.m_[4]), A.m_[6]),
                           mul(mul(A.m_[1], A.m_[3]), A.m_[8])),
                       mul(mul(A.m_[0], A.m_[5]), A.m_[7])));
    } else {
        DenseMatrix B = DenseMatrix(n, n, A.m_);
        unsigned i, sign = 1;
        RCP<const Basic> d;

        for (unsigned k = 0; k < n - 1; k++) {
            if (eq(*(B.m_[k * n + k]), *zero)) {
                for (i = k + 1; i < n; i++)
                    if (neq(*(B.m_[i * n + k]), *zero)) {
                        row_exchange_dense(B, i, k);
                        sign *= -1;
                        break;
                    }
                if (i == n)
                    return zero;
            }

            for (i = k + 1; i < n; i++) {
                for (unsigned j = k + 1; j < n; j++) {
                    d = sub(mul(B.m_[k * n + k], B.m_[i * n + j]),
                            mul(B.m_[i * n + k], B.m_[k * n + j]));
                    if (k > 0)
                        d = div(d, B.m_[(k - 1) * n + k - 1]);
                    B.m_[i * n + j] = d;
                }
            }
        }

        return (sign == 1) ? B.m_[n * n - 1] : mul(minus_one, B.m_[n * n - 1]);
    }
}
예제 #20
0
RCP<const Set> Interval::set_union(const RCP<const Set> &o) const
{
    if (is_a<Interval>(*o)) {
        const Interval &other = static_cast<const Interval &>(*o);
        RCP<const Basic> start_start, end_end, m;
        RCP<const Number> start, end;
        bool left_open, right_open;
        start_start = max({this->start_, other.start_});
        end_end = min({this->end_, other.end_});
        m = min({start_start, end_end});
        if ((eq(*end_end, *start_start) and eq(*end_end, *m)
             and ((eq(*end_end, *this->end_) and this->right_open_)
                  or (eq(*end_end, *other.end_) and other.right_open_)))
            or (eq(*end_end, *m) and not eq(*end_end, *start_start))) {
            return SymEngine::set_union({rcp_from_this_cast<const Set>(), o},
                                        false);
        } else {
            if (eq(*min({this->start_, other.start_}), *this->start_))
                start = this->start_;
            else
                start = other.start_;
            if (eq(*max({this->end_, other.end_}), *this->end_))
                end = this->end_;
            else
                end = other.end_;
            left_open = ((neq(*this->start_, *start) or this->left_open_)
                         and (neq(*other.start_, *start) or other.left_open_));
            right_open = ((neq(*this->end_, *end) or this->right_open_)
                          and (neq(*other.end_, *end) or other.right_open_));
            return interval(start, end, left_open, right_open);
        }
    }
    if (is_a<UniversalSet>(*o) or is_a<EmptySet>(*o) or is_a<FiniteSet>(*o)
        or is_a<Union>(*o)) {
        return (*o).set_union(rcp_from_this_cast<const Set>());
    }
    return SymEngine::set_union({rcp_from_this_cast<const Set>(), o}, false);
}
예제 #21
0
 static RCP<const Basic> diff(const FunctionSymbol &self,
         const RCP<const Symbol> &x) {
     RCP<const Basic> diff = zero, t;
     RCP<const Basic> self_ = self.rcp_from_this();
     RCP<const Symbol> s;
     std::string name;
     unsigned count  = 0;
     bool found_x = false;
     for (const auto &a : self.get_args()) {
         if (eq(*a, *x)) {
             found_x = true;
             count++;
         } else if (count < 2 and neq(*a->diff(x), *zero)) {
             count++;
         }
     }
     if (count == 1 and found_x) {
         return Derivative::create(self_, {x});
     }
     for (unsigned i = 0; i < self.get_args().size(); i++) {
         t = self.get_args()[i]->diff(x);
         if (neq(*t, *zero)) {
             name = "x";
             do {
                 name = "_" + name;
                 s = symbol(name);
             } while (has_symbol(*self_, s));
             vec_basic v = self.get_args();
             v[i] = s;
             map_basic_basic m;
             insert(m, v[i], self.get_args()[i]);
             diff = add(diff, mul(t,
                 make_rcp<const Subs>(Derivative::create(self.create(v),
                         {v[i]}), m)));
         }
     }
     return diff;
 }
예제 #22
0
void CSRMatrix::set(unsigned i, unsigned j, const RCP<const Basic> &e)
{
    SYMENGINE_ASSERT(i < row_ and j < col_);

    unsigned k = p_[i];
    unsigned row_end = p_[i + 1];
    unsigned end = p_[i + 1];
    unsigned mid;

    while (k < end) {
        mid = (k + end) / 2;
        if (mid == k) {
            if (j_[k] < j) {
                k++;
            }
            break;
        } else if (j_[mid] >= j and j_[mid - 1] < j) {
            k = mid;
            break;
        } else if (j_[mid - 1] >= j) {
            end = mid - 1;
        } else {
            k = mid + 1;
        }
    }

    if (neq(*e, *zero)) {
        if (k < row_end and j_[k] == j) {
            x_[k] = e;
        } else { // j_[k] > j or k is the last non-zero element
            x_.insert(x_.begin() + k, e);
            j_.insert(j_.begin() + k, j);
            for (unsigned l = i + 1; l <= row_; l++)
                p_[l]++;
        }
    } else {                              // e is zero
        if (k < row_end and j_[k] == j) { // remove existing non-zero element
            x_.erase(x_.begin() + k);
            j_.erase(j_.begin() + k);
            for (unsigned l = i + 1; l <= row_; l++)
                p_[l]--;
        }
    }
}
예제 #23
0
파일: add.cpp 프로젝트: achabill/symengine
void Add::as_coef_term(const RCP<const Basic> &self,
        const Ptr<RCP<const Number>> &coef, const Ptr<RCP<const Basic>> &term)
{
    if (is_a<Mul>(*self)) {
        if (neq(*(rcp_static_cast<const Mul>(self)->coef_), *one)) {
            *coef = (rcp_static_cast<const Mul>(self))->coef_;
            // We need to copy our 'dict_' here, as 'term' has to have its own.
            map_basic_basic d2 = (rcp_static_cast<const Mul>(self))->dict_;
            *term = Mul::from_dict(one, std::move(d2));
        } else {
            *coef = one;
            *term = self;
        }
    } else if (is_a_Number(*self)) {
        *coef = rcp_static_cast<const Number>(self);
        *term = one;
    } else {
        SYMENGINE_ASSERT(not is_a<Add>(*self));
        *coef = one;
        *term = self;
    }
}
예제 #24
0
// SymPy LUDecomposition_Simple algorithm, in
// sympy.matrices.matrices.Matrix.LUdecomposition_Simple with pivoting.
// P must be an initialized matrix and will be permuted.
void pivoted_LU(const DenseMatrix &A, DenseMatrix &LU, permutelist &pl)
{
    SYMENGINE_ASSERT(A.row_ == A.col_ and LU.row_ == LU.col_);
    SYMENGINE_ASSERT(A.row_ == LU.row_);

    unsigned n = A.row_;
    unsigned i, j, k;
    RCP<const Basic> scale;
    int pivot;

    LU.m_ = A.m_;

    for (j = 0; j < n; j++) {
        for (i = 0; i < j; i++)
            for (k = 0; k < i; k++)
                LU.m_[i * n + j] = sub(LU.m_[i * n + j],
                                       mul(LU.m_[i * n + k], LU.m_[k * n + j]));
        pivot = -1;
        for (i = j; i < n; i++) {
            for (k = 0; k < j; k++) {
                LU.m_[i * n + j] = sub(LU.m_[i * n + j],
                                       mul(LU.m_[i * n + k], LU.m_[k * n + j]));
            }
            if (pivot == -1 and neq(*LU.m_[i * n + j], *zero))
                pivot = i;
        }
        if (pivot == -1)
            throw SymEngineException("Matrix is rank deficient");
        if (pivot - j != 0) { // row must be swapped
            row_exchange_dense(LU, pivot, j);
            pl.push_back({pivot, j});
        }
        scale = div(one, LU.m_[j * n + j]);

        for (i = j + 1; i < n; i++)
            LU.m_[i * n + j] = mul(LU.m_[i * n + j], scale);
    }
}
예제 #25
0
// Compute C = A (binary_op) B for CSR matrices that are in the
// canonical CSR format. Matrix dimensions of A and B should be the
// same. C will be in canonical format as well.
void csr_binop_csr_canonical(
    const CSRMatrix &A, const CSRMatrix &B, CSRMatrix &C,
    RCP<const Basic>(&bin_op)(const RCP<const Basic> &,
                              const RCP<const Basic> &))
{
    SYMENGINE_ASSERT(A.row_ == B.row_ and A.col_ == B.col_ and C.row_ == A.row_
                     and C.col_ == A.col_);

    // Method that works for canonical CSR matrices
    C.p_[0] = 0;
    unsigned nnz = 0;
    unsigned A_pos, B_pos, A_end, B_end;

    for (unsigned i = 0; i < A.row_; i++) {
        A_pos = A.p_[i];
        B_pos = B.p_[i];
        A_end = A.p_[i + 1];
        B_end = B.p_[i + 1];

        // while not finished with either row
        while (A_pos < A_end and B_pos < B_end) {
            unsigned A_j = A.j_[A_pos];
            unsigned B_j = B.j_[B_pos];

            if (A_j == B_j) {
                RCP<const Basic> result = bin_op(A.x_[A_pos], B.x_[B_pos]);
                if (neq(*result, *zero)) {
                    C.j_.push_back(A_j);
                    C.x_.push_back(result);
                    nnz++;
                }
                A_pos++;
                B_pos++;
            } else if (A_j < B_j) {
                RCP<const Basic> result = bin_op(A.x_[A_pos], zero);
                if (neq(*result, *zero)) {
                    C.j_.push_back(A_j);
                    C.x_.push_back(result);
                    nnz++;
                }
                A_pos++;
            } else {
                // B_j < A_j
                RCP<const Basic> result = bin_op(zero, B.x_[B_pos]);
                if (neq(*result, *zero)) {
                    C.j_.push_back(B_j);
                    C.x_.push_back(result);
                    nnz++;
                }
                B_pos++;
            }
        }

        // tail
        while (A_pos < A_end) {
            RCP<const Basic> result = bin_op(A.x_[A_pos], zero);
            if (neq(*result, *zero)) {
                C.j_.push_back(A.j_[A_pos]);
                C.x_.push_back(result);
                nnz++;
            }
            A_pos++;
        }
        while (B_pos < B_end) {
            RCP<const Basic> result = bin_op(zero, B.x_[B_pos]);
            if (neq(*result, *zero)) {
                C.j_.push_back(B.j_[B_pos]);
                C.x_.push_back(result);
                nnz++;
            }
            B_pos++;
        }

        C.p_[i + 1] = nnz;
    }

    // It's enough to check for duplicates as the column indices
    // remain sorted after the above operations
    if (CSRMatrix::csr_has_duplicates(C.p_, C.j_, A.row_))
        CSRMatrix::csr_sum_duplicates(C.p_, C.j_, C.x_, A.row_);
}
예제 #26
0
RCP<const Basic> pow_expand(const RCP<const Pow> &self)
{
    RCP<const Basic> _base = expand(self->base_);
    bool negative_pow = false;
    if (! is_a<Integer>(*self->exp_) || ! is_a<Add>(*_base)) {
        if (neq(_base, self->base_)) {
            return pow(_base, self->exp_);
        } else {
            return self;
        }
    }

    map_vec_mpz r;
    int n = rcp_static_cast<const Integer>(self->exp_)->as_int();
    if (n < 0) {
        n = -n;
        negative_pow = true;
    }
    RCP<const Add> base = rcp_static_cast<const Add>(_base);
    umap_basic_num base_dict = base->dict_;
    if (! (base->coef_->is_zero())) {
        // Add the numerical coefficient into the dictionary. This
        // allows a little bit easier treatment below.
        insert(base_dict, base->coef_, one);
    }
    int m = base_dict.size();
    multinomial_coefficients_mpz(m, n, r);
    umap_basic_num rd;
    // This speeds up overall expansion. For example for the benchmark
    // (y + x + z + w)^60 it improves the timing from 135ms to 124ms.
    rd.reserve(2*r.size());
    RCP<const Number> add_overall_coeff=zero;
    for (auto &p: r) {
        auto power = p.first.begin();
        auto i2 = base_dict.begin();
        map_basic_basic d;
        RCP<const Number> overall_coeff=one;
        for (; power != p.first.end(); ++power, ++i2) {
            if (*power > 0) {
                RCP<const Integer> exp = rcp(new Integer(*power));
                RCP<const Basic> base = i2->first;
                if (is_a<Integer>(*base)) {
                    imulnum(outArg(overall_coeff),
                        rcp_static_cast<const Number>(
                        rcp_static_cast<const Integer>(base)->powint(*exp)));
                } else if (is_a<Symbol>(*base)) {
                    Mul::dict_add_term(d, exp, base);
                } else {
                    RCP<const Basic> exp2, t, tmp;
                    tmp = pow(base, exp);
                    if (is_a<Mul>(*tmp)) {
                        for (auto &p: (rcp_static_cast<const Mul>(tmp))->dict_) {
                            Mul::dict_add_term_new(outArg(overall_coeff), d,
                                    p.second, p.first);
                        }
                        imulnum(outArg(overall_coeff), (rcp_static_cast<const Mul>(tmp))->coef_);
                    } else {
                        Mul::as_base_exp(tmp, outArg(exp2), outArg(t));
                        Mul::dict_add_term_new(outArg(overall_coeff), d, exp2, t);
                    }
                }
                if (!(i2->second->is_one())) {
                    if (is_a<Integer>(*(i2->second)) || is_a<Rational>(*(i2->second))) {
                        imulnum(outArg(overall_coeff),
                        pownum(i2->second,
                            rcp_static_cast<const Number>(exp)));
                    } else if (is_a<Complex>(*(i2->second))) {
                        RCP<const Number> tmp = rcp_static_cast<const Complex>(i2->second)->pow(*exp);
                        imulnum(outArg(overall_coeff), tmp);
                    }
                }
            }
        }
        RCP<const Basic> term = Mul::from_dict(overall_coeff, std::move(d));
        RCP<const Number> coef2 = rcp(new Integer(p.second));
        if (is_a_Number(*term)) {
            iaddnum(outArg(add_overall_coeff),
                mulnum(rcp_static_cast<const Number>(term), coef2));
        } else {
            if (is_a<Mul>(*term) &&
                    !(rcp_static_cast<const Mul>(term)->coef_->is_one())) {
                // Tidy up things like {2x: 3} -> {x: 6}
                imulnum(outArg(coef2),
                        rcp_static_cast<const Mul>(term)->coef_);
                // We make a copy of the dict_:
                map_basic_basic d2 = rcp_static_cast<const Mul>(term)->dict_;
                term = Mul::from_dict(one, std::move(d2));
            }
            Add::dict_add_term(rd, coef2, term);
        }
    }
    RCP<const Basic> result = Add::from_dict(add_overall_coeff, std::move(rd));
    if (negative_pow) result = pow(result, minus_one);
    return result;
}
예제 #27
0
void Conditions::Neq(const string& name, const string& value) {
    shared_ptr<Condition::Base> neq(new Condition::Neq(name, value));
    vector< shared_ptr<Condition::Base> >::push_back(neq);
}
예제 #28
0
void ReactorNet::initialize()
{
    size_t n, nv;
    char buf[100];
    m_nv = 0;
    m_reactors.clear();
    m_nreactors = 0;
    writelog("Initializing reactor network.\n", m_verbose);
    if (m_nr == 0)
        throw CanteraError("ReactorNet::initialize",
                           "no reactors in network!");
    size_t sensParamNumber = 0;
    for (n = 0; n < m_nr; n++) {
        if (m_r[n]->type() >= ReactorType) {
            m_r[n]->initialize(m_time);
            Reactor* r = (Reactor*)m_r[n];
            m_reactors.push_back(r);
            nv = r->neq();
            m_size.push_back(nv);
            m_nparams.push_back(r->nSensParams());
            std::vector<std::pair<void*, int> > sens_objs = r->getSensitivityOrder();
            for (size_t i = 0; i < sens_objs.size(); i++) {
                std::map<size_t, size_t>& s = m_sensOrder[sens_objs[i]];
                for (std::map<size_t, size_t>::iterator iter = s.begin();
                        iter != s.end();
                        ++iter) {
                    m_sensIndex.resize(std::max(iter->second + 1, m_sensIndex.size()));
                    m_sensIndex[iter->second] = sensParamNumber++;
                }
            }
            m_nv += nv;
            m_nreactors++;

            if (m_verbose) {
                sprintf(buf,"Reactor %s: %s variables.\n",
                        int2str(n).c_str(), int2str(nv).c_str());
                writelog(buf);
                sprintf(buf,"            %s sensitivity params.\n",
                        int2str(r->nSensParams()).c_str());
                writelog(buf);
            }
            if (m_r[n]->type() == FlowReactorType && m_nr > 1) {
                throw CanteraError("ReactorNet::initialize",
                                   "FlowReactors must be used alone.");
            }
        }
    }

    m_connect.resize(m_nr*m_nr,0);
    m_ydot.resize(m_nv,0.0);
    size_t i, j, nin, nout, nw;
    ReactorBase* r, *rj;
    for (i = 0; i < m_nr; i++) {
        r = m_reactors[i];
        for (j = 0; j < m_nr; j++) {
            if (i == j) {
                connect(i,j);
            } else {
                rj = m_reactors[j];
                nin = rj->nInlets();
                for (n = 0; n < nin; n++) {
                    if (&rj->inlet(n).out() == r) {
                        connect(i,j);
                    }
                }
                nout = rj->nOutlets();
                for (n = 0; n < nout; n++) {
                    if (&rj->outlet(n).in() == r) {
                        connect(i,j);
                    }
                }
                nw = rj->nWalls();
                for (n = 0; n < nw; n++) {
                    if (&rj->wall(n).left() == rj
                            && &rj->wall(n).right() == r) {
                        connect(i,j);
                    } else if (&rj->wall(n).left() == r
                               && &rj->wall(n).right() == rj) {
                        connect(i,j);
                    }
                }
            }
        }
    }

    m_atol.resize(neq());
    fill(m_atol.begin(), m_atol.end(), m_atols);
    m_integ->setTolerances(m_rtol, neq(), DATA_PTR(m_atol));
    m_integ->setSensitivityTolerances(m_rtolsens, m_atolsens);
    m_integ->setMaxStepSize(m_maxstep);
    m_integ->setMaxErrTestFails(m_maxErrTestFails);
    if (m_verbose) {
        sprintf(buf, "Number of equations: %s\n", int2str(neq()).c_str());
        writelog(buf);
        sprintf(buf, "Maximum time step:   %14.6g\n", m_maxstep);
        writelog(buf);
    }
    m_integ->initialize(m_time, *this);
    m_init = true;
}
예제 #29
0
	static bool loopCond(std::pair<t9, ff::ptr<int>> loopState)
	{
		ff::ptr<int> s = ff::snd(loopState);
		return neq(ff::deref(s), 0);
	};
예제 #30
0
파일: hasChar.cpp 프로젝트: JPMoresmau/HNC
	bool loopCond(ff::ptr<int> s)
	{
		return and(neq(c, ff::deref(s)), neq(ff::deref(s), 0));
	};