Esempio n. 1
0
    def __init__(self, ndps, labels=None):
        from mcdp_posets.types_universe import get_types_universe
        if not isinstance(ndps, tuple) or not len(ndps) >= 1:
            raise_desc(ValueError, 'Expected a nonempty tuple.', ndps=ndps)

        if labels is not None:
            if not isinstance(labels, tuple) or not len(labels) == len(ndps):
                raise_desc(ValueError, 'Need labels to be consistent',
                           ndps=ndps, labels=labels)
        self.labels = labels

        tu = get_types_universe()
        first = ndps[0]
        ftypes = first.get_ftypes(first.get_fnames())
        rtypes = first.get_rtypes(first.get_rnames())

        for i, ndp in enumerate(ndps):
            ftypes_i = ndp.get_ftypes(ndp.get_fnames())
            rtypes_i = ndp.get_rtypes(ndp.get_rnames())
            name = 'model #%d' % i if not self.labels else self.labels[i].__repr__()
            try:
                tu.check_equal(ftypes, ftypes_i)
            except NotEqual as e:
                msg = 'Cannot create co-product: ftypes of %s do not match the first.' % name
                raise_wrapped(ValueError, e, msg,
                              ftypes=ftypes, ftypes_i=ftypes_i)

            try:
                tu.check_equal(rtypes, rtypes_i)
            except NotEqual as e:
                msg = 'Cannot create co-product: rtypes of %s not match the first.' % name
                raise_wrapped(ValueError, e, msg,
                              rtypes=rtypes, rtypes_i=rtypes_i)

        self.ndps = ndps
Esempio n. 2
0
def get_common(ua, ub):
    Pa = ua.P
    Pb = ub.P

    if not isinstance(Pa, PosetProduct) or not isinstance(Pb, PosetProduct):
        raise NotImplementedError((Pa, Pb))

    # first, it might be that they have different spaces

    # let's find out how to match them

    tu = get_types_universe()
    # for each i in Pa, we will match it to the first
    matches1 = []
    for i, P in enumerate(Pa.subs):
        for j, Q in enumerate(Pb.subs):
            if ('B', j) in matches1: continue
            if tu.leq(P, Q):
                matches1.append(('B', j))
                break
        else:
            matches1.append(('A', i))
    matches2 = []
    for j, Q in enumerate(Pb.subs):
        if ('B', j) in matches1:
            # used by somebody
            matches2.append(('B', j))
        else:
            for i, P in enumerate(Pa.subs):
                if matches1[i] is not None: continue
                if tu.leq(Q, P):
                    matches2.append(('A', i))
                    break
            else:
                matches2.append(('B', j))

    print('matches1:  %s' % matches1)
    print('matches2: %s' % matches2)

    used = sorted(set(matches1 + matches2))

    def get_P(_):
        (which, index) = _
        if which == 'A': return Pa.subs[index]
        if which == 'B': return Pb.subs[index]
        assert False

    Ps = PosetProduct(tuple(map(get_P, used)))
    print('used: %s' % used)
    print('Ps: %s' % Ps)

    # now we need to complete the first
    Ps_a = get(matches1, used, Ps, get_P, Pa, ua)
    Ps_b = get(matches2, used, Ps, get_P, Pb, ub)

    print('Ps_a: %s' % Ps_a)
    print('Ps_b: %s' % Ps_b)

    S = UpperSets(Ps)
    return S, Ps_a, Ps_b
Esempio n. 3
0
def check_embedding21():
    # In general P ~= PosetProduct((P,)) 
    # but we don't do it yet.
    P = Rcomp()
    S = PosetProduct((P, ))
    tu = get_types_universe()
    _, _ = tu.get_embedding(P, S)
def get_common(ua, ub):
    Pa = ua.P
    Pb = ub.P

    if not isinstance(Pa, PosetProduct) or not isinstance(Pb, PosetProduct):
        raise NotImplementedError((Pa, Pb))

    # first, it might be that they have different spaces

    # let's find out how to match them

    tu = get_types_universe()
    # for each i in Pa, we will match it to the first
    matches1 = []
    for i, P in enumerate(Pa.subs):
        for j, Q in enumerate(Pb.subs):
            if ('B', j) in matches1: continue
            if tu.leq(P, Q):
                matches1.append(('B', j))
                break
        else:
            matches1.append(('A', i))
    matches2 = []
    for j, Q in enumerate(Pb.subs):
        if ('B', j) in matches1:
            # used by somebody
            matches2.append(('B', j))
        else:
            for i, P in enumerate(Pa.subs):
                if matches1[i] is not None: continue
                if tu.leq(Q, P):
                    matches2.append(('A', i))
                    break
            else:
                matches2.append(('B', j))

    print('matches1:  %s' % matches1)
    print('matches2: %s' % matches2)

    used = sorted(set(matches1 + matches2))
    def get_P(_):
        (which, index) = _
        if which == 'A': return Pa.subs[index]
        if which == 'B': return Pb.subs[index]
        assert False

    Ps = PosetProduct(tuple(map(get_P, used)))
    print('used: %s' % used)
    print('Ps: %s' % Ps)

    # now we need to complete the first
    Ps_a = get(matches1, used, Ps, get_P, Pa, ua)
    Ps_b = get(matches2, used, Ps, get_P, Pb, ub)

    print('Ps_a: %s' % Ps_a)
    print('Ps_b: %s' % Ps_b)

    S = UpperSets(Ps)
    return S, Ps_a, Ps_b
Esempio n. 5
0
    def process(self, request, string, nl, nu):
        l = self.get_library(request)
        parsed = l.parse_constant(string)

        space = parsed.unit
        value = parsed.value

        model_name = self.get_model_name(request)
        library = self.get_current_library_name(request)
        ndp, dp = self._get_ndp_dp(library, model_name)

        F = dp.get_fun_space()
        UR = UpperSets(dp.get_res_space())

        tu = get_types_universe()
        tu.check_leq(parsed.unit, F)

        f = express_value_in_isomorphic_space(parsed.unit, parsed.value, F)

        print('query: %s ...' % F.format(f))

        from mocdp import logger
        tracer = Tracer(logger=logger)

        dpl, dpu = get_dp_bounds(dp, nl, nu)

        intervals = False
        max_steps = 10000
        result_l, _trace = solve_meat_solve(tracer, ndp, dpl, f,
                                         intervals, max_steps, False)

        result_u, trace = solve_meat_solve(tracer, ndp, dpu, f,
                                         intervals, max_steps, False)


        key = (string, nl, nu)

        res = dict(result_l=result_l, result_u=result_u, dpl=dpl, dpu=dpu)
        self.solutions[key] = res

        res = {}

        e = cgi.escape

        res['output_space'] = e(space.__repr__() + '\n' + str(type(space)))
        res['output_raw'] = e(value.__repr__() + '\n' + str(type(value)))
        res['output_formatted'] = e(space.format(value))

        res['output_result'] = 'Lower: %s\nUpper: %s' % (UR.format(result_l),
                                                         UR.format(result_u))
        res['output_trace'] = str(trace)

        encoded = "nl=%s&nu=%s&string=%s" % (nl, nu, string)
        res['output_image'] = 'display.png?' + encoded
        res['ok'] = True

        return res
Esempio n. 6
0
def check_type_universe1():

    tu = get_types_universe()

    R1 = parse_poset('dimensionless')
    R2 = parse_poset('dimensionless')
    assert R1 == R2

    tu.check_equal(R1, R2)
    tu.check_leq(R1, R2)
    _embed1, _embed2 = tu.get_embedding(R1, R2)
Esempio n. 7
0
def check_unit_conversions2():


    tu = get_types_universe()

    A = make_rcompunit('mph')
    B = make_rcompunit('m/s')
    assert not A == B

    tu.check_leq(A, B)
    tu.check_leq(B, A)
    assert not tu.equal(A, B)

    B_from_A, A_from_B = tu.get_embedding(A, B)
    print('B_from_A: %s' % B_from_A)
    print('A_from_B: %s' % A_from_B)

    tu.check_equal(B_from_A.dom, A)
    tu.check_equal(B_from_A.cod, B)
    tu.check_equal(A_from_B.dom, B)
    tu.check_equal(A_from_B.cod, A)

    print('B_from_A: %s  a=1.0 B_from_A(1.0) = %s' % (B_from_A, B_from_A(1.0)))
    assert_allclose(B_from_A(1.0), ONE_MPH_IN_M_S)
    assert_allclose(A_from_B(ONE_MPH_IN_M_S), 1.0)


    ndp = parse_ndp("""
mcdp {  
    provides a [m/s] 
    provides b [mph]

    requires c [m/s]
    requires d [mph]

    c >= a + b
    d >= a + b
}
    """)
    print ndp.repr_long()
    dp = ndp.get_dp()
    print dp.repr_long()
    cases = (
      ((0.0, 1.0), (ONE_MPH_IN_M_S, 1.0)),
      ((1.0, 0.0), (1.0, 1.0 / ONE_MPH_IN_M_S)),
    )

    for func, expected in cases:
        print('func: %s   F = %s' % (str(func), dp.get_fun_space()))
        print('expected: %s' % str(expected))
        r = dp.solve(func)
        print('obtained: %s %s' % (str(r), dp.get_res_space()))
        limit = list(r.minimals)[0]
        assert_allclose(limit, expected)
Esempio n. 8
0
def check_type_universe1():

    tu = get_types_universe()

    R1 = parse_poset('dimensionless')
    R2 = parse_poset('dimensionless')
    assert R1 == R2

    tu.check_equal(R1, R2)
    tu.check_leq(R1, R2)
    _embed1, _embed2 = tu.get_embedding(R1, R2)
Esempio n. 9
0
def check_unit_conversions2():

    tu = get_types_universe()

    A = make_rcompunit('mph')
    B = make_rcompunit('m/s')
    assert not A == B

    tu.check_leq(A, B)
    tu.check_leq(B, A)
    assert not tu.equal(A, B)

    B_from_A, A_from_B = tu.get_embedding(A, B)
    print('B_from_A: %s' % B_from_A)
    print('A_from_B: %s' % A_from_B)

    tu.check_equal(B_from_A.dom, A)
    tu.check_equal(B_from_A.cod, B)
    tu.check_equal(A_from_B.dom, B)
    tu.check_equal(A_from_B.cod, A)

    print('B_from_A: %s  a=1.0 B_from_A(1.0) = %s' % (B_from_A, B_from_A(1.0)))
    assert_allclose(B_from_A(1.0), ONE_MPH_IN_M_S)
    assert_allclose(A_from_B(ONE_MPH_IN_M_S), 1.0)

    ndp = parse_ndp("""
mcdp {  
    provides a [m/s] 
    provides b [mph]

    requires c [m/s]
    requires d [mph]

    c >= a + b
    d >= a + b
}
    """)
    print ndp.repr_long()
    dp = ndp.get_dp()
    print dp.repr_long()
    cases = (
        ((0.0, 1.0), (ONE_MPH_IN_M_S, 1.0)),
        ((1.0, 0.0), (1.0, 1.0 / ONE_MPH_IN_M_S)),
    )

    for func, expected in cases:
        print('func: %s   F = %s' % (str(func), dp.get_fun_space()))
        print('expected: %s' % str(expected))
        r = dp.solve(func)
        print('obtained: %s %s' % (str(r), dp.get_res_space()))
        limit = list(r.minimals)[0]
        assert_allclose(limit, expected)
Esempio n. 10
0
    def __init__(self, ndps, labels=None):
        from mcdp_posets.types_universe import get_types_universe
        if not isinstance(ndps, tuple) or not len(ndps) >= 1:
            raise_desc(ValueError, 'Expected a nonempty tuple.', ndps=ndps)

        if labels is not None:
            if not isinstance(labels, tuple) or not len(labels) == len(ndps):
                raise_desc(ValueError,
                           'Need labels to be consistent',
                           ndps=ndps,
                           labels=labels)
        self.labels = labels

        tu = get_types_universe()
        first = ndps[0]
        ftypes = first.get_ftypes(first.get_fnames())
        rtypes = first.get_rtypes(first.get_rnames())

        for i, ndp in enumerate(ndps):
            ftypes_i = ndp.get_ftypes(ndp.get_fnames())
            rtypes_i = ndp.get_rtypes(ndp.get_rnames())
            name = 'model #%d' % i if not self.labels else self.labels[
                i].__repr__()
            try:
                tu.check_equal(ftypes, ftypes_i)
            except NotEqual as e:
                msg = 'Cannot create co-product: ftypes of %s do not match the first.' % name
                raise_wrapped(ValueError,
                              e,
                              msg,
                              ftypes=ftypes,
                              ftypes_i=ftypes_i)

            try:
                tu.check_equal(rtypes, rtypes_i)
            except NotEqual as e:
                msg = 'Cannot create co-product: rtypes of %s not match the first.' % name
                raise_wrapped(ValueError,
                              e,
                              msg,
                              rtypes=rtypes,
                              rtypes_i=rtypes_i)

        self.ndps = ndps
Esempio n. 11
0
def less_resources2(ua, ub):
    """
    
        ua must be <= ub
    """
    Pa = ua.P
    Pb = ub.P

    if not isinstance(Pa, PosetProduct) or not isinstance(Pb, PosetProduct):
        raise NotImplementedError((Pa, Pb))

    tu = get_types_universe()

    matches = []
    for i, P in enumerate(Pa.subs):
        for j, Q in enumerate(Pb.subs):
            if j in matches: continue
            if tu.leq(P, Q):
                matches.append(j)
                break
        else:
            # msg = 'Could not find match.'
            return False

    # now we have found an embedding

    # first we create a projection for Pb
    m1 = MuxMap(F=Pb, coords=matches)

    ub2 = upperset_project_map(ub, m1)
    Pb2 = ub2.P
    UPb2 = UpperSets(Pb2)

    # now we create the embedding
    A_to_B, _ = tu.get_embedding(Pa, Pb2)
    ua2 = upperset_project_map(ua, A_to_B)

    print('Pa: %s' % Pa)
    print('Pb2:  %s' % Pb2)
    print('ua2: %s' % ua2)
    print('ub2: %s' % ub2)

    return UPb2.leq(ua2, ub2)
def less_resources2(ua, ub):
    """
    
        ua must be <= ub
    """
    Pa = ua.P
    Pb = ub.P

    if not isinstance(Pa, PosetProduct) or not isinstance(Pb, PosetProduct):
        raise NotImplementedError((Pa, Pb))

    tu = get_types_universe()

    matches = []
    for i, P in enumerate(Pa.subs):
        for j, Q in enumerate(Pb.subs):
            if j in matches: continue
            if tu.leq(P, Q):
                matches.append(j)
                break
        else:
            # msg = 'Could not find match.'
            return False

    # now we have found an embedding

    # first we create a projection for Pb
    m1 = MuxMap(F=Pb, coords=matches)

    ub2 = upperset_project_map(ub, m1)
    Pb2 = ub2.P
    UPb2 = UpperSets(Pb2)

    # now we create the embedding
    A_to_B, _ = tu.get_embedding(Pa, Pb2)
    ua2 = upperset_project_map(ua, A_to_B)

    print('Pa: %s' % Pa)
    print('Pb2:  %s' % Pb2)
    print('ua2: %s' % ua2)
    print('ub2: %s' % ub2)

    return UPb2.leq(ua2, ub2)
Esempio n. 13
0
    def __init__(self, maps):
        """ 
            maps = [f, g, h]
            === h o g o f
            
            They are in order of application.
        """
        self.maps = tuple(maps)
        from mcdp_posets.types_universe import get_types_universe

        tu = get_types_universe()
        for i in range(len(maps) - 1):
            first = maps[i]
            second = maps[i + 1]
            cod1 = first.get_codomain()
            dom2 = second.get_domain()
            tu.check_equal(cod1, dom2)

        mcdp_dev_warning('Check that the composition makes sense')
        dom = self.maps[0].get_domain()
        cod = self.maps[-1].get_codomain()
        Map.__init__(self, dom=dom, cod=cod)
Esempio n. 14
0
    def __init__(self, maps):
        """ 
            maps = [f, g, h]
            === h o g o f
            
            They are in order of application.
        """
        self.maps = tuple(maps)
        from mcdp_posets.types_universe import get_types_universe

        tu = get_types_universe()
        for i in range(len(maps)-1):
            first = maps[i]
            second =maps[i+1]
            cod1 = first.get_codomain()
            dom2 = second.get_domain()
            tu.check_equal(cod1, dom2)

        mcdp_dev_warning('Check that the composition makes sense')
        dom = self.maps[0].get_domain()
        cod = self.maps[-1].get_codomain()
        Map.__init__(self, dom=dom, cod=cod)
Esempio n. 15
0
def check_consistent_data(names, fnames, rnames, connections):
    from mocdp.comp.context import get_name_for_res_node, get_name_for_fun_node
    from mocdp.comp.context import is_res_node_name
    from mcdp_posets.types_universe import get_types_universe
    tu = get_types_universe()

    for n in names:
        try:
            check_good_name(n)
        except ValueError as e:
            msg = 'This name is not good.'
            raise_wrapped(ValueError, e, msg, names=names)

        isit, x = is_fun_node_name(n)
        if isit and not x in fnames:
            msg = 'The name for the node seems to be the one for a function.'
            raise_desc(ValueError, msg, n=n, fnames=fnames)

        isit, x = is_res_node_name(n)
        if isit and not x in rnames:
            if not n in rnames:
                msg = 'The name for the node seems to be the one for a resource.'
                raise_desc(ValueError, msg, n=n, rnames=rnames)

    for f in fnames:
        fnode = get_name_for_fun_node(f)
        if not fnode in names:
            msg = 'Expecting to see a node with the name of the function.'
            raise_desc(ValueError, msg, f=f, names=list(names.keys()))

        fn = names[fnode]
        if not f in fn.get_fnames():
            msg = ('Expecting to see the special function node have function '
                   'with function name.')
            raise_desc(ValueError,
                       msg,
                       f=f,
                       fnode=fnode,
                       fn=fn,
                       fn_fnames=fn.get_fnames())

    for r in rnames:
        rnode = get_name_for_res_node(r)
        if not rnode in names:
            msg = 'Expecting to see a node with the name of the resource.'
            raise_desc(ValueError, msg, r=r, names=list(names.keys()))

        rn = names[rnode]
        if not r in rn.get_rnames():
            msg = ('Expecting to see the special resource node have resource '
                   'with resource name.')
            raise_desc(ValueError,
                       msg,
                       r=r,
                       rnode=rnode,
                       rn=rn,
                       rn_rnames=rn.get_rnames())

    for c in connections:
        try:
            if not c.dp1 in names:
                raise_desc(ValueError,
                           'First DP %r not found.' % c.dp1,
                           name=c.dp1,
                           available=list(names))

            if not c.s1 in names[c.dp1].get_rnames():
                raise_desc(ValueError,
                           'Resource %r of first DP %r not found' %
                           (c.s1, c.dp1),
                           rname=c.s1,
                           available=names[c.dp1].get_rnames())

            if not c.dp2 in names:
                raise_desc(ValueError,
                           'Second DP %r not found.' % c.dp2,
                           name=c.dp2,
                           available=list(names))

            if not c.s2 in names[c.dp2].get_fnames():
                raise_desc(ValueError,
                           'Function %r of second DP %r not found.' %
                           (c.s2, c.dp2),
                           s2=c.s2,
                           available=names[c.dp2].get_fnames())

            R = names[c.dp1].get_rtype(c.s1)
            F = names[c.dp2].get_ftype(c.s2)

            try:
                tu.check_equal(R, F)
            except NotEqual as e:
                msg = 'Invalid connection %s' % c.__repr__()
                raise_wrapped(ValueError, e, msg, R=R, F=F)

        except ValueError as e:
            msg = 'Invalid connection %s.' % (c.__repr__())
            raise_wrapped(ValueError, e, msg, compact=True)
Esempio n. 16
0
def check_consistent_data(names, fnames, rnames, connections):
    from mocdp.comp.context import get_name_for_res_node, get_name_for_fun_node
    from mocdp.comp.context import is_res_node_name
    from mcdp_posets.types_universe import get_types_universe
    tu = get_types_universe()

    for n in names:
        try:
            check_good_name(n)
        except ValueError as e:
            msg = 'This name is not good.'
            raise_wrapped(ValueError, e, msg, names=names)

        isit, x = is_fun_node_name(n)
        if isit and not x in fnames:
            msg = 'The name for the node seems to be the one for a function.'
            raise_desc(ValueError, msg, n=n, fnames=fnames)

        isit, x = is_res_node_name(n)
        if isit and not x in rnames:
            if not n in rnames:
                msg = 'The name for the node seems to be the one for a resource.'
                raise_desc(ValueError, msg, n=n, rnames=rnames)

    for f in  fnames:
        fnode = get_name_for_fun_node(f)
        if not fnode in names:
            msg = 'Expecting to see a node with the name of the function.'
            raise_desc(ValueError, msg, f=f, names=list(names.keys()))

        fn = names[fnode]
        if not f in fn.get_fnames():
            msg = ('Expecting to see the special function node have function '
                   'with function name.')
            raise_desc(ValueError, msg, f=f, fnode=fnode, fn=fn,
                        fn_fnames=fn.get_fnames())

    for r in  rnames:
        rnode = get_name_for_res_node(r)
        if not rnode in names:
            msg = 'Expecting to see a node with the name of the resource.'
            raise_desc(ValueError, msg, r=r, names=list(names.keys()))

        rn = names[rnode]
        if not r in rn.get_rnames():
            msg = ('Expecting to see the special resource node have resource '
                   'with resource name.')
            raise_desc(ValueError, msg, r=r, rnode=rnode, rn=rn,
                       rn_rnames=rn.get_rnames())


    for c in connections:
        try:
            if not c.dp1 in names:
                raise_desc(ValueError, 'First DP %r not found.' % c.dp1, name=c.dp1,
                           available=list(names))

            if not c.s1 in names[c.dp1].get_rnames():
                raise_desc(ValueError, 'Resource %r of first DP %r not found' %( c.s1, c.dp1),
                           rname=c.s1, available=names[c.dp1].get_rnames())

            if not c.dp2 in names:
                raise_desc(ValueError, 'Second DP %r not found.' % c.dp2, name=c.dp2,
                           available=list(names))

            if not c.s2 in names[c.dp2].get_fnames():
                raise_desc(ValueError, 'Function %r of second DP %r not found.' % (c.s2, c.dp2),
                           s2=c.s2, available=names[c.dp2].get_fnames())

            R = names[c.dp1].get_rtype(c.s1)
            F = names[c.dp2].get_ftype(c.s2)

            try:
                tu.check_equal(R, F)
            except NotEqual as e:
                msg = 'Invalid connection %s' % c.__repr__()
                raise_wrapped(ValueError, e, msg, R=R, F=F)

        except ValueError as e:
            msg = 'Invalid connection %s.' % (c.__repr__())
            raise_wrapped(ValueError, e, msg, compact=True)