Example #1
0
def check_products():
    F1 = R_Weight
    F2 = R_Time
    F3 = R_Energy
    M, pack, unpack = get_product_compact(F1, F2, F3)

    print(M)
    s = pack(F1.get_top(), F2.get_bottom(), F3.get_top())
    print(s)
    u = unpack(s)
    assert_equal(u, s)

    F1 = R_Time
    F2 = PosetProduct(())
    F3 = R_Energy
    F = PosetProduct((F1, F2, F3))
    print('F: %s' % F)
    M, pack, unpack = get_product_compact(F1, F2, F3)

    print('M: %s' % M)
    element = (F1.get_top(), F2.get_bottom(), F3.get_top())
    print('elements: %s' % F.format(element))
    s = pack(*element)
    print('packed: %s' % str(s))
    u = unpack(s)
    print('depacked: %s' % str(u))
    assert_equal(u, element)
Example #2
0
def check_square():
    I = Interval(0.0, 1.0)
    P = PosetProduct((I, I))

    assert P.get_bottom() == (0.0, 0.0)
    assert P.get_top() == (1.0, 1.0)

    assert P.leq((0.0, 0.0), (0.0, 0.5))
    assert not P.leq((0.0, 0.1), (0.0, 0.0))
Example #3
0
def eval_constant_MakeTuple(op, context):
    ops = get_odd_ops(unwrap_list(op.ops))
    constants = [eval_constant(_, context) for _ in ops]
    # TODO: generic product
    Fs = [_.unit for _ in constants]
    vs = [_.value for _ in constants]
    F = PosetProduct(tuple(Fs))
    v = tuple(vs)
    F.belongs(v)
    return ValueWithUnits(v, F)
Example #4
0
def check_products2():
    print('------')
    F1 = PosetProduct(())
    M, pack, unpack = get_product_compact(F1)

    print('M: %s' % M)
    element = ()
    F1.belongs(element)
    print('elements: %s' % F1.format(element))
    
    s = pack(*(element,))
    print('packed: %s' % str(s))
    u,  = unpack(s)
    print('depacked: %s' % str(u))
    assert_equal(u, element)
Example #5
0
    def __init__(self, Fs, R):
        for _ in Fs:
            check_isinstance(_, RcompUnits)
        check_isinstance(R, RcompUnits)
        self.Fs = Fs
        self.R = R

        sum_dimensionality_works(Fs, R)

        dom = PosetProduct(self.Fs)
        cod = R

        Map.__init__(self, dom=dom, cod=cod)
Example #6
0
def check_coproduct1():
    S1 = R_Weight
    S2 = PosetProduct((R_Time, R_Energy))

    C = Coproduct1((S1, S2))

    x = C.witness()
    C.belongs(x)
    print C.format(x)

    
    i, xi = C.unpack(x)
    
    if i == 0:
        S1.belongs(xi)
    elif i == 1:
        S2.belongs(xi)
    else:
        assert False

    r = C.pack(i, xi)
    C.check_equal(r, x)
    def _execute(self, dp1, dp2): 
        a = dp1
        b = dp2
        One = PosetProduct(())
        assert a.get_res_space() == One and b.get_res_space() == One
        
        mux = Mux(One, [(), ()])
         
        solutions_a = a.solve_r(())
        solutions_b = b.solve_r(())
        prod = lowerset_product(solutions_a, solutions_b)
        F = PosetProduct((a.get_fun_space(), b.get_fun_space()))
        elements = prod.maximals
        if len(elements) == 1:
            e = list(elements)[0]
            F.belongs(e)
            dpconstant = Limit(F, e)
        else:
            dpconstant = LimitMaximals(F, elements)

        res = Series( dpconstant, mux)
        return res
Example #8
0
def its_dp_as_product(ndp):
    """ If fnames == 1 """
    dp = ndp.get_dp()
    if len(ndp.get_fnames()) == 1:
        F0 = dp.get_fun_space()
        F = PosetProduct((F0, ))
        down = Mux(F, 0)
        dp = make_series(down, dp)

    if len(ndp.get_rnames()) == 1:
        R0 = dp.get_res_space()
        lift = Mux(R0, [()])
        dp = make_series(dp, lift)
    return dp
Example #9
0
    def __init__(self, Fs, R):
        dom = PosetProduct(Fs)
        cod = R
        Map.__init__(self, dom=dom, cod=cod)

        tu = get_types_universe()
        self.subs = []
        target = Int()
        for F in Fs:
            # need F to be cast to Int
            F_to_Int, _ = tu.get_embedding(F, target)
            self.subs.append(F_to_Int)

        self.to_R, _ = tu.get_embedding(target, R)
Example #10
0
def dpgraph(name2dp, connections, split):
    """ 
    
        This assumes that the graph is weakly connected
        and that there are no repetitions of names of resources
        or functions.
        
        It also assumes that each function/resource 
        is connected to exactly one function/resource.
        
    """
    if not len(set(split)) == len(split):
        raise ValueError('dpgraph: Repeated signals in split: %s' % str(split))

    if not(name2dp):
        assert not connections
        assert not split
        dp = Mux(PosetProduct(()), [])
        return dpwrap(dp, [], [])

    rmc = find_resources_with_multiple_connections(connections)
    if rmc:
        msg = 'These resources have multiple connections.'
        raise_desc(ValueError, msg, rmc=rmc)

    fmc = find_functions_with_multiple_connections(connections)
    if fmc:
        msg = 'These resources have multiple connections.'
        raise_desc(ValueError, msg, fmc=fmc)

    # check that there are no repetitions
    if there_are_reps(name2dp):
        name2dp_, connections_, relabeling = relabel(name2dp, connections)
        print('relabeling: %s' % relabeling)
        assert not there_are_reps(name2dp_)
        # XXX: what do we do with split?
        return dpgraph(name2dp_, connections_, split)

    res = dpgraph_(name2dp, connections, split)

    try:
        for x in split:
            res.rindex(x)
    except DPInternalError as e:
        msg = 'Invalid result from dpgraph_().'
        raise_wrapped(DPInternalError, e, msg, res=res,
                      name2dp=name2dp, connections=connections,
                   split=split)
    return res
Example #11
0
    def _execute(self, dp1, dp2):
        One = PosetProduct(())
        OneOne = PosetProduct((One, One))
        mux = Mux(OneOne, [])

        One = PosetProduct(())
        a = dp1
        b = dp2
        assert a.get_fun_space() == One and b.get_fun_space() == One
        try:
            solutions_a = a.solve(())
            solutions_b = b.solve(())
        except (NotSolvableNeedsApprox, NotImplementedError):
            raise

        prod = upperset_product(solutions_a, solutions_b)
        R = PosetProduct((a.get_res_space(), b.get_res_space()))
        if len(prod.minimals) == 1:
            dpconstant = Constant(R, list(prod.minimals)[0])
        else:
            dpconstant = ConstantMinimals(R, prod.minimals)

        res = Series(mux, dpconstant)
        return res
Example #12
0
def opt_basic_2():
    l1 = parse_poset('J').U(1.0)
    l2 = parse_poset('m x J').U((1.0, 1.0))
    n1 = (1, )
    n2 = (1, )
    N = PosetProduct((Nat(), ))

    # create a joint one
    l1b = add_extra(l1, N, n1)
    l2b = add_extra(l2, N, n2)

    print l1b
    print l2b

    assert less_resources2(l1b, l2b)
    assert not less_resources2(l2b, l1b)
Example #13
0
def pmin2():
    n = 300
    ndim = 2
    Pbase = wrap_with_counts(Rcomp())
    N2 = PosetProduct((Pbase, ) * ndim)

    print('Using random antichain')
    # point_generation = lambda n: get_random_points(n, ndim, m)
    # Ps = get_random_antichain(n, point_generation, N2.leq)
    P1 = get_random_antichain(n, ndim)
    P2 = get_random_antichain(n, ndim)
    Ps = set()
    Ps.update(P1)
    Ps.update(P2)

    run_all(N2, Ps)
Example #14
0
def eval_MakeTuple_as_lfunction(mt, context):
    from mcdp_lang.eval_lfunction_imp import eval_lfunction

    ops = get_odd_ops(unwrap_list(mt.ops))
    functions = [eval_lfunction(_, context) for _ in ops]
    Rs = [context.get_ftype(_) for _ in functions]
    R = PosetProduct(tuple(Rs))

    # Now it's easy - this corresponds to a simple Mux operation
    coords = list(range(len(Rs)))
    dp = TakeRes(R, coords)

    return create_operation_lf(context,
                               dp=dp,
                               functions=functions,
                               name_prefix='_demake_tuple',
                               op_prefix='_factors',
                               res_prefix='_result')
Example #15
0
def report_dp1(dp, imp=None):
    r = Report()
    gg = dp_graph_flow(dp, imp=imp)
    gg_figure(r, 'graph', gg)

    r.text('long', dp.repr_long())
    #
    #     try:
    #         S, alpha, beta = dp.get_normal_form()
    #
    #         s = ""
    #         s += 'S: %s' % S
    #         s += '\nα: %s' % alpha
    #         s += '\nβ: %s' % beta
    #
    #         r.text('normalform', s)
    #         r.text('tree_long', dp.tree_long())
    #     except Exception as e:
    #         warnings.warn('Normal form not implemented %s' % e)

    M = dp.get_imp_space()
    r.text('I', str(M))

    if False:
        R = dp.get_res_space()
        F = dp.get_fun_space()
        Rinf = R.get_top()
        Fbot = F.get_bottom()
        if M == PosetProduct((R_dimensionless, )):
            s = ""
            ms = [0.0, 0.25, 0.5, 0.75, 1.0]
            for m in ms:
                feasible = dp.is_feasible(Fbot, (m, ), Rinf)
                s += '\n m = %s  = %s' % (m, feasible)
            r.text('scalarres', s)
        else:
            m = M.witness()
            print(Fbot, m, Rinf)
            feasible = dp.is_feasible(Fbot, m, Rinf)
            r.text('some',
                   'bot feasible( %s, %s,%s): %s' % (Fbot, m, Rinf, feasible))

    return r
Example #16
0
def eval_rvalue_MakeTuple(mt, context):
    from mcdp_lang.eval_resources_imp import eval_rvalue

    ops = get_odd_ops(unwrap_list(mt.ops))
    resources = [eval_rvalue(_, context) for _ in ops]
    Fs = [context.get_rtype(_) for _ in resources]
    F = PosetProduct(tuple(Fs))

    # Now it's easy - this corresponds to a simple Mux operation
    n = len(Fs)
    coords = list(range(n))
    dp = TakeFun(F, coords)

    return create_operation(context,
                            dp=dp,
                            resources=resources,
                            name_prefix='_make_tuple',
                            op_prefix='_factors',
                            res_prefix='_result')
Example #17
0
def make_parallel(dp1, dp2):
    from mcdp_dp.dp_series_simplification import disable_optimization
    if disable_optimization:
        return Parallel(dp1, dp2)

    from mcdp_dp.dp_series_simplification import equiv_to_identity

    # change identity to Mux
    a = Parallel(dp1, dp2)
    if equiv_to_identity(dp1) and equiv_to_identity(dp2):
        F = PosetProduct((dp1.get_fun_space(), dp2.get_fun_space()))
        assert F == a.get_fun_space()
        return IdentityDP(F)

#     if False:
#         # These never run...
#
#         # Parallel(X, Terminator) => Series(Mux([0]), X, Mux([0, ()]))
#         if is_equiv_to_terminator(dp2):
#             F = a.get_fun_space()  # PosetProduct((dp1.get_fun_space(),))
#             m1 = Mux(F, coords=0)
#             m2 = dp1
#             m3 = Mux(m2.get_res_space(), [(), []])
#             res = make_series(make_series(m1, m2), m3)
#
#             assert res.get_res_space() == a.get_res_space()
#             assert res.get_fun_space() == a.get_fun_space()
#             return res
#
#         if is_equiv_to_terminator(dp1):
#             F = a.get_fun_space()  # PosetProduct((dp1.get_fun_space(),))
#             m1 = Mux(F, coords=1)
#             m2 = dp2
#             m3 = Mux(m2.get_res_space(), [[], ()])
#             return make_series(make_series(m1, m2), m3)

    for rule in rules:
        if rule.applies(dp1, dp2):
            # logger.debug('Applying par. simplification rule %s' % type(rule).__name__)
            return rule.execute(dp1, dp2)

    return Parallel(dp1, dp2)
Example #18
0
    def applies(self, dp1, dp2):
        a = dp1
        b = dp2

        One = PosetProduct(())
        if not (a.get_res_space() == One and b.get_res_space() == One):
            return False

        if self.only_for_limit:
            allowed = (Limit, LimitMaximals)
            if not (isinstance(a, allowed) and isinstance(b, allowed)):
                return False

        try:
            solutions_a = a.solve_r(())  # @UnusedVariable
            solutions_b = b.solve_r(())  # @UnusedVariable
        except (NotSolvableNeedsApprox, NotImplementedError):
            return False

        return True
Example #19
0
def opt_basic_7():
    libnames = ['actuation']
    library = get_test_library2(libnames)

    #     outdir = 'out/opt_basic_7'
    #     cache_dir = os.path.join(outdir, 'cache')
    library.use_tmp_cache()
    ndp = library.load_ndp('duckiebot_sol00')

    min_functions = {
        'motion': '< `RigidBodyID: rb1, 0.1 m/s, 10 minutes >',
    }
    _flabels, F0s, f0s = _parse_dict(min_functions, library)

    names = [name for name, _ndp in cndp_get_name_ndp_notfunres(ndp)]
    print('names: %s' % names)

    to_remove = list(names)
    to_remove.remove('dagu_chassis')
    # to_remove.remove('battery_ravpower')
    # to_remove.remove('USBMicroCharging')

    from mcdp_opt_tests.ndp_utils import cndp_remove_one_child
    for n in to_remove:
        ndp = cndp_remove_one_child(ndp, n)

    print ndp

    if len(F0s) > 1:
        F = PosetProduct(F0s)
        f0 = f0s
    else:
        F = F0s[0]
        f0 = f0s[0]

    dp = ndp.get_dp()
    F1 = dp.get_fun_space()

    f1 = express_value_in_isomorphic_space(F, f0, F1)

    _res = dp.solve(f1)
Example #20
0
    def axis_for_sequence(self, space, seq):
        self.check_plot_space(space)

        R2 = PosetProduct((Rcomp(), Rcomp()))
        self.R2 = R2
        #         tu = get_types_universe()
        #         P_TO_S, _ = tu.get_embedding(space.P, R2)

        maxx, maxy = 1000.0, 1000.0

        def limit(p):
            x, y = p
            x = min(x, maxx)
            y = min(y, maxy)
            return x, y

        points2d = [[(limit(self.P_to_S(_))) for _ in s.minimals] for s in seq]

        axes = [get_bounds(_) for _ in points2d]
        merged = functools.reduce(reduce_bounds, axes)
        return merged
Example #21
0
def check_get_names_used1():

    # . L . . . . . . . \ Parallel2  % R[kg]×(R[N]×R[N]) -> R[kg]×R[W] I = PosetProduct(R[kg],PosetProduct(R[N],R[N]){actuati
    # on/_prod1},R[N²]) names: [('actuation', '_prod1')]
    # . L . . . . . . . . \ Id(R[kg]) I = R[kg]
    # . L . . . . . . . . \ Series: %  R[N]×R[N] -> R[W] I = PosetProduct(PosetProduct(R[N],R[N]){actuation/_prod1},R[N²]) nam
    # es: [('actuation', '_prod1'), ('actuation', '_mult1')]
    # . L . . . . . . . . . \ ProductN(R[N]×R[N] -> R[N²]) named: ('actuation', '_prod1') I = PosetProduct(R[N],R[N])
    # . L . . . . . . . . . \ GenericUnary(<mcdp_lang.misc_math.MultValue instance at 0x10d8dcbd8>) named: ('actuation', '_mult1
    # ') I = R[N²]
    att = MCDPConstants.ATTRIBUTE_NDP_RECURSIVE_NAME
    S1 = parse_poset('N')
    setattr(S1, att, ('S1', ))
    S2 = parse_poset('kg')
    setattr(S2, att, ('S2', ))
    S12 = PosetProduct((S1, S2))
    names = get_names_used(S12)
    assert names == [('S1', ), ('S2', )], names
    P = parse_poset('J x W')
    setattr(P, att, ('prod', ))

    S, _pack, _unpack = get_product_compact(P, S12)
    print S.__repr__()
    assert get_names_used(S) == [('prod', ), ('S1', ), ('S2', )]
Example #22
0
def eval_ndp_catalogue3(r, context):
    check_isinstance(r, CDP.Catalogue3)

    statements = unwrap_list(r.funres)
    fun = [x for x in statements if isinstance(x, CDP.FunStatement)]
    res = [x for x in statements if isinstance(x, CDP.ResStatement)]
    Fs = [eval_space(_.unit, context) for _ in fun]
    Rs = [eval_space(_.unit, context) for _ in res]

    assert len(fun) + len(res) == len(statements), statements

    tu = get_types_universe()

    rows = unwrap_list(r.table)

    entries = []  # (name, f, r)

    for i, row in enumerate(rows):
        check_isinstance(row, CDP.CatalogueRow3)

        check_isinstance(row.functions, CDP.CatalogueFunc)
        row.leftright
        check_isinstance(row.resources, CDP.CatalogueRes)

        fs = get_odd_ops(unwrap_list(row.functions.ops))
        rs = get_odd_ops(unwrap_list(row.resources.ops))

        for _ in list(fs) + list(rs):
            if isinstance(_, CDP.CatalogueEntryConstantUncertain):
                msg = 'Uncertain catalogue not implemented'
                raise DPNotImplementedError(msg, where=_.where)

        fs_evaluated = [eval_constant(_.constant, context) for _ in fs]
        rs_evaluated = [eval_constant(_.constant, context) for _ in rs]

        if len(Fs) == 0:
            # expect <>
            if len(fs) != 1 and fs_evaluated.value != ():
                msg = 'Because there are no functionalities, I expected simply "<>".'
                raise DPSemanticError(msg, where=row.functions.where)
        else:
            if len(fs_evaluated) != len(Fs):
                msg = 'Mismatch with number of functionalities.'
                raise DPSemanticError(msg, where=row.functions.where)

        if len(Rs) == 0:
            if len(rs) != 1 and rs_evaluated.value != ():
                msg = 'Because there are no resources, I expected simply "<>".'
                raise DPSemanticError(msg, where=row.resources.where)
        else:
            if len(rs_evaluated) != len(Rs):
                msg = 'Mismatch with number of resources.'
                raise DPSemanticError(msg, where=row.resources.where)

        for cell, Fhave, F in zip(fs, fs_evaluated, Fs):
            try:
                tu.check_leq(Fhave.unit, F)
            except NotLeq:
                msg = 'Dimensionality problem: cannot convert %s to %s.' % (
                    Fhave.unit, F)
                raise DPSemanticError(msg, where=cell.where)

        for cell, Rhave, R in zip(rs, rs_evaluated, Rs):
            try:
                tu.check_leq(Rhave.unit, R)
            except NotLeq:
                msg = 'Dimensionality problem: cannot convert %s to %s.' % (
                    Rhave.unit, R)
                raise DPSemanticError(msg, where=cell.where)

        fvalues_ = [_.cast_value(F) for (_, F) in zip(fs_evaluated, Fs)]
        rvalues_ = [_.cast_value(R) for (_, R) in zip(rs_evaluated, Rs)]

        assert len(fvalues_) == len(fun)
        assert len(rvalues_) == len(res)

        f = tuple(fvalues_)
        r = tuple(rvalues_)

        if len(Fs) == 0:
            f = ()
        if len(Rs) == 0:
            r = ()

        entries.append((i, f, r))

    names = set([name for (name, _, _) in entries])

    M = FiniteCollectionAsSpace(names)
    # use integers
    # entries = [(float(i), b, c) for i, (_, b, c) in enumerate(entries)]

    fnames = [_.fname.value for _ in fun]
    rnames = [_.rname.value for _ in res]

    if len(Fs) == 1:
        F = Fs[0]
        fnames = fnames[0]
        entries = [(a, b[0], c) for (a, b, c) in entries]
    else:
        F = PosetProduct(tuple(Fs))

    if len(Rs) == 1:
        R = Rs[0]
        rnames = rnames[0]
        entries = [(a, b, c[0]) for (a, b, c) in entries]
    else:
        R = PosetProduct(tuple(Rs))

    dp = CatalogueDP(F=F, R=R, I=M, entries=tuple(entries))
    ndp = dpwrap(dp, fnames=fnames, rnames=rnames)
    return ndp
Example #23
0
def eval_ndp_catalogue(r, context):
    check_isinstance(r, CDP.FromCatalogue)
    # FIXME:need to check for re-ordering
    statements = unwrap_list(r.funres)
    fun = [x for x in statements if isinstance(x, CDP.FunStatement)]
    res = [x for x in statements if isinstance(x, CDP.ResStatement)]

    Fs = [eval_space(_.unit, context) for _ in fun]
    Rs = [eval_space(_.unit, context) for _ in res]

    assert len(fun) + len(res) == len(statements), statements
    tu = get_types_universe()
    table = r.table
    rows = unwrap_list(table.rows)
    entries = []
    for row in rows:
        items = unwrap_list(row)
        name = items[0].value
        expected = 1 + len(fun) + len(res)
        if len(items) != expected:
            msg = 'Row with %d elements does not match expected of elements (%s fun, %s res)' % (
                len(items), len(fun), len(res))
            # msg += ' items: %s' % str(items)
            raise DPSemanticError(msg, where=items[-1].where)
        fvalues0 = items[1:1 + len(fun)]
        rvalues0 = items[1 + len(fun):1 + len(fun) + len(res)]

        fvalues = [eval_constant(_, context) for _ in fvalues0]
        rvalues = [eval_constant(_, context) for _ in rvalues0]

        for cell, Fhave, F in zip(fvalues0, fvalues, Fs):
            try:
                tu.check_leq(Fhave.unit, F)
            except NotLeq as e:
                msg = 'Dimensionality problem: cannot convert %s to %s.' % (
                    Fhave.unit, F)
                ex = lambda msg: DPSemanticError(msg, where=cell.where)
                raise_wrapped(ex, e, msg, compact=True)

        for cell, Rhave, R in zip(rvalues0, rvalues, Rs):
            try:
                tu.check_leq(Rhave.unit, R)
            except NotLeq as e:
                msg = 'Dimensionality problem: cannot convert %s to %s.' % (
                    Rhave.unit, R)
                ex = lambda msg: DPSemanticError(msg, where=cell.where)
                raise_wrapped(ex, e, msg, compact=True)

        fvalues_ = [_.cast_value(F) for (_, F) in zip(fvalues, Fs)]
        rvalues_ = [_.cast_value(R)for (_, R) in zip(rvalues, Rs)]

        assert len(fvalues_) == len(fun)
        assert len(rvalues_) == len(res)

        entries.append((name, tuple(fvalues_), tuple(rvalues_)))

    names = set([name for (name, _, _) in entries])
    M = FiniteCollectionAsSpace(names)
    # use integers
    # entries = [(float(i), b, c) for i, (_, b, c) in enumerate(entries)]

    fnames = [_.fname.value for _ in fun]
    rnames = [_.rname.value for _ in res]

    if len(Fs) == 1:
        F = Fs[0]
        fnames = fnames[0]
        entries = [(a, b[0], c) for (a, b, c) in entries]
    else:
        F = PosetProduct(tuple(Fs))

    if len(Rs) == 1:
        R = Rs[0]
        rnames = rnames[0]
        entries = [(a, b, c[0]) for (a, b, c) in entries]
    else:
        R = PosetProduct(tuple(Rs))

    dp = CatalogueDP(F=F, R=R, I=M, entries=tuple(entries))
    ndp = dpwrap(dp, fnames=fnames, rnames=rnames)
    return ndp
Example #24
0
def eval_ndp_dpwrap(r, context):
    tu = get_types_universe()

    statements = unwrap_list(r.statements)
    fun = [x for x in statements if isinstance(x, CDP.FunStatement)]
    res = [x for x in statements if isinstance(x, CDP.ResStatement)]

    assert len(fun) + len(res) == len(statements), statements
    impl = r.impl

    from .eval_primitivedp_imp import eval_primitivedp
    dp = eval_primitivedp(impl, context)

    fnames = [f.fname.value for f in fun]
    rnames = [r.rname.value for r in res]

    if len(fnames) == 1:
        use_fnames = fnames[0]
    else:
        use_fnames = fnames
    if len(rnames) == 1:
        use_rnames = rnames[0]
    else:
        use_rnames = rnames

    dp_F = dp.get_fun_space()
    dp_R = dp.get_res_space()

    # Check that the functions are the same
    want_Fs = tuple([eval_space(f.unit, context) for f in fun])
    if len(want_Fs) == 1:
        want_F = want_Fs[0]
    else:
        want_F = PosetProduct(want_Fs)

    want_Rs = tuple([eval_space(r.unit, context) for r in res])
    if len(want_Rs) == 1:
        want_R = want_Rs[0]
    else:
        want_R = PosetProduct(want_Rs)

    mcdp_dev_warning('Not sure about this')
    dp_prefix = get_conversion(want_F, dp_F)
    dp_postfix = get_conversion(dp_R, want_R)

    if dp_prefix is not None:
        dp = make_series(dp_prefix, dp)

    if dp_postfix is not None:
        dp = make_series(dp, dp_postfix)

    try:
        w = SimpleWrap(dp=dp, fnames=use_fnames, rnames=use_rnames)
    except ValueError as e:
        raise DPSemanticError(str(e), r.where)

    ftypes = w.get_ftypes(fnames)
    rtypes = w.get_rtypes(rnames)
    ftypes_expected = PosetProduct(
        tuple([eval_space(f.unit, context) for f in fun]))
    rtypes_expected = PosetProduct(
        tuple([eval_space(r.unit, context) for r in res]))

    try:
        tu.check_equal(ftypes, ftypes_expected)
        tu.check_equal(rtypes, rtypes_expected)
    except NotEqual as e:
        msg = 'The types in the description do not match.'
        raise_wrapped(DPSemanticError, e, msg,
                      dp=dp,
                      ftypes=ftypes,
                      ftypes_expected=ftypes_expected,
                      rtypes=rtypes,
                      rtypes_expected=rtypes_expected, compact=True)

    return w
Example #25
0
 def __init__(self):
     R = Rcomp()
     self.S = PosetProduct((PosetProduct((R, R)), R))
Example #26
0
 def __init__(self, F, Rs):
     R = PosetProduct(Rs)
     self.F = F
     self.Rs = Rs
     M = PosetProduct((F, R))
     PrimitiveDP.__init__(self, F=F, R=R, I=M)
Example #27
0
def add_muxes(inner,
              cs,
              s_muxed,
              inner_name='_inner0',
              mux1_name='_mux1',
              mux2_name='_mux2'):
    """
        Add muxes before and after inner 
        
       
                  ---(extraf)--|       |---(extrar)--
                     |--c1-----| inner |--c1--|
             s_muxed-|--c2-----|       |--c2--|--s_muxed
           
    """

    extraf = [f for f in inner.get_fnames() if not f in cs]
    extrar = [r for r in inner.get_rnames() if not r in cs]

    fnames = extraf + [s_muxed]
    rnames = extrar + [s_muxed]

    name2ndp = {}
    connections = []
    name2ndp[inner_name] = inner

    # Second mux
    if len(cs) == 1:
        F = inner.get_ftype(cs[0])
        nto1 = SimpleWrap(Identity(F), fnames=cs[0], rnames=s_muxed)
    else:
        types = inner.get_ftypes(cs)
        F = PosetProduct(types.subs)
        # [0, 1, 2]
        coords = list(range(len(cs)))
        mux = Mux(F, coords)
        nto1 = SimpleWrap(mux, fnames=cs, rnames=s_muxed)

    if len(cs) == 1:
        R = inner.get_rtype(cs[0])
        _1ton = SimpleWrap(Identity(R), fnames=s_muxed, rnames=cs[0])
    else:

        # First mux
        coords = list(range(len(cs)))
        R = mux.get_res_space()
        mux2 = Mux(R, coords)
        _1ton = SimpleWrap(mux2, fnames=s_muxed, rnames=cs)
        F2 = mux2.get_res_space()
        tu = get_types_universe()
        tu.check_equal(F, F2)

    name2ndp[mux1_name] = nto1
    name2ndp[mux2_name] = _1ton

    for n in cs:
        connections.append(Connection(inner_name, n, mux1_name, n))
    for n in cs:
        connections.append(Connection(mux2_name, n, inner_name, n))

    # Now add the remaining names
    connect_functions_to_outside(name2ndp,
                                 connections,
                                 ndp_name=inner_name,
                                 fnames=extraf)
    connect_resources_to_outside(name2ndp,
                                 connections,
                                 ndp_name=inner_name,
                                 rnames=extrar)

    connect_resources_to_outside(name2ndp,
                                 connections,
                                 ndp_name=mux1_name,
                                 rnames=[s_muxed])
    connect_functions_to_outside(name2ndp,
                                 connections,
                                 ndp_name=mux2_name,
                                 fnames=[s_muxed])

    outer = CompositeNamedDP.from_parts(name2ndp=name2ndp,
                                        connections=connections,
                                        fnames=fnames,
                                        rnames=rnames)
    return outer
Example #28
0
def check_loop_result3():
    
    parse_wrap(Syntax.primitivedp_expr,
                     'code mcdp_dp_tests.inv_mult_plots.CounterMap___(n=3)')[0]

    parse_wrap(Syntax.ndpt_simple_dp_model,
                     """
                     dp {
        requires x [Nat]
        provides c [Nat]

        implemented-by code mcdp_dp_tests.inv_mult_plots.CounterMap___(n=3)
    }
                     """)[0]


    assert_semantic_error("""
mcdp {
    s = instance dp {
        requires x [Nat]
        provides c [Nat]

        # semantic error: does not exist
        implemented-by code mcdp_dp_tests.inv_mult_plots.CounterMap___(n=3)
    }
   
}"""
    )

    assert_semantic_error("""
mcdp {
    s = instance dp {
        requires x [Nat]
        provides c [Nat]

        # semantic error: not a DP
        implemented-by code mcdp_dp_tests.inv_mult_plots.CounterMap(n=3)
    }
   
}"""
    )
    
    ndp = parse_ndp("""
mcdp {
    adp1 = dp {
        requires x [Nat]
        provides c [Nat]

        implemented-by code mcdp_dp_tests.inv_mult_plots.CounterDP(n=3)
    }

    s = instance adp1 
    
    s.c >= s.x
   
}"""
    )
    
#     UNat = UpperSets(Nat())

    dp = ndp.get_dp()
    print dp
    res = dp.solve(())
    print res.__repr__()
    One = PosetProduct(())
    U1 = UpperSets(One)
    U1.check_equal(res, One.U(()))

    ndp = parse_ndp("""
mcdp {
    adp1 = dp {
        requires x [Nat]
        provides c [Nat]

        implemented-by code mcdp_dp_tests.inv_mult_plots.CounterDP(n=3)
    }
    
    adp2 = dp {
        requires x [Nat]
        provides c [Nat]

        implemented-by code mcdp_dp_tests.inv_mult_plots.CounterDP(n=2)
    }

    s = instance choose(a: adp1, b: adp2)
    
    s.c >= s.x
   
    requires x for s
}"""
    )
    N = Nat()
    UNat = UpperSets(N)
    dp = ndp.get_dp()
    print dp
    res = dp.solve(())
    print res
    UNat.check_equal(res, N.U(2))
Example #29
0
 def __init__(self, n, P):
     dom = PosetProduct((P, ) * n)
     cod = P
     Map.__init__(self, dom, cod)
     self.P = P
     self.n = n
Example #30
0
def connect2(ndp1, ndp2, connections, split, repeated_ok=False):
    """ 
        Note the argument split must be a list of strings so 
        that orders are preserved and deterministic. 
    """

    if ndp1 is ndp2:
        raise ValueError('Equal')

    def common(x, y):
        return len(set(x + y)) != len(set(x)) + len(set(y))

    if not repeated_ok:
        if (common(ndp1.get_fnames(), ndp2.get_fnames())
                or common(ndp1.get_rnames(), ndp2.get_rnames())):
            raise_desc(DPInternalError,
                       'repeated names',
                       ndp1=ndp1,
                       ndp2=ndp2,
                       connections=connections,
                       split=split)

    if len(set(split)) != len(split):
        msg = 'Repeated signals in split: %s' % str(split)
        raise ValueError(msg)
    try:
        if not connections:
            raise ValueError('Empty connections')

        #     |   |------------------------->A
        #     |   |          |-B1(split)----->
        # f1->|   |--B1----->|         ___
        #     | 1 |          |----B2->|   |   all_s2 = B2 + C2  all_s1 = B1 + C1
        #     |___| -C1--C2---------->| 2 |->r2
        # ---------D----------------->|___|
        #
        # ftot = f1 + D
        # rtot = A + b1 + r2
        # A + B + C = r1
        # B + C + D = f2
        # split = A + B

        # split = B1 is given
        # find B2 from B1
        def s2_from_s1(s1):
            for c in connections:
                if c.s1 == s1: return c.s2
            assert False, 'Cannot find connection with s1 = %s' % s1

        def s1_from_s2(s2):
            for c in connections:
                if c.s2 == s2: return c.s1
            assert False, 'Cannot find connection with s2 = %s' % s2

        f1 = ndp1.get_fnames()
        r1 = ndp1.get_rnames()
        f2 = ndp2.get_fnames()
        r2 = ndp2.get_rnames()

        all_s2 = set([c.s2 for c in connections])
        all_s1 = set([c.s1 for c in connections])

        # assert that all split are in s1
        for x in split:
            assert x in all_s1

        B1 = list(split)
        B2 = map(s2_from_s1, B1)
        C2 = list_diff(all_s2, B2)
        C1 = map(s1_from_s2, C2)
        A = list_diff(r1, B1 + C1)
        D = list_diff(f2, B2 + C2)

        # print('B1: %s' % B1)
        # print('B2: %s' % B2)
        # print('C2: %s' % C1)
        # print('C1: %s' % C1)
        # print(' A: %s' % A)
        # print(' D: %s' % D)
        fntot = f1 + D
        rntot = A + B1 + r2

        if there_are_repetitions(fntot) or there_are_repetitions(rntot):
            raise_desc(NotImplementedError,
                       'Repeated names',
                       fnames=fntot,
                       rnames=fntot)

        # now I can create Ftot and Rtot
        f1_types = ndp1.get_ftypes(f1)

        D_types = ndp2.get_ftypes(D)
        #         print('f1: %s' % f1)
        #         print('f1 types: %s' % f1_types)
        #         print('D: %s' % D)
        #         print('D types: %s' % D_types)

        Ftot = PosetProduct(tuple(list(f1_types) + list(D_types)))
        Rtot = PosetProduct(
            tuple(
                list(ndp1.get_rtypes(A)) + list(ndp1.get_rtypes(B1)) +
                list(ndp2.get_rtypes(r2))))

        # print('Ftot: %s' % str(Ftot))
        # print('      %s' % str(fntot))
        # print('Rtot: %s' % str(Rtot))
        # print('      %s' % str(rntot))
        assert len(fntot) == len(Ftot), (fntot, Ftot)
        assert len(rntot) == len(Rtot), (rntot, Rtot)

        # I can create the first muxer m1
        # from ftot to Product(f1, D)

        m1_for_f1 = [fntot.index(s) for s in f1]
        m1_for_D = [fntot.index(s) for s in D]

        m1coords = [m1_for_f1, m1_for_D]
        m1 = Mux(Ftot, m1coords)

        # print('m1: %s' % m1)
        # print('m1.R: %s' % m1.get_res_space())

        # Get Identity on D
        D_types = ndp2.get_ftypes(D)
        Id_D = Identity(D_types)

        ndp1_p = its_dp_as_product(ndp1)
        X = make_parallel(ndp1_p, Id_D)

        # make sure we can connect
        m1_X = make_series(m1, X)

        # print('m1_X = %s' % m1_X)
        # print('m1_X.R = %s' % m1_X.get_res_space()  )

        def coords_cat(c1, m):
            if m != ():
                return c1 + (m, )
            else:
                return c1

        A_B1_types = PosetProduct(
            tuple(ndp1.get_rtypes(A)) + tuple(ndp1.get_rtypes(B1)))
        Id_A_B1 = Identity(A_B1_types)
        ndp2_p = its_dp_as_product(ndp2)
        Z = make_parallel(Id_A_B1, ndp2_p)
        # print('Z.R = %s' % Z.get_res_space())
        # print('B1: %s' % B1)
        # print('R2: %s' % r2)
        m2coords_A = [(0, (A + B1).index(x)) for x in A]
        m2coords_B1 = [(0, (A + B1).index(x)) for x in B1]
        m2coords_r2 = [(1, r2.index(x)) for x in r2]
        m2coords = m2coords_A + m2coords_B1 + m2coords_r2
        # print('m2coords_A: %r' % m2coords_A)
        # print('m2coords_B1: %r' % m2coords_B1)
        # print('m2coords_r2: %r' % m2coords_r2)
        # print('m2coords: %r' % m2coords)

        # print('Z.R: %s' % Z.get_res_space())
        m2 = Mux(Z.get_res_space(), m2coords)

        assert len(m2.get_res_space()) == len(rntot), ((m2.get_res_space(),
                                                        rntot))
        # make sure we can connect
        make_series(Z, m2)

        #
        #  f0 -> |m1| -> | X | -> |Y |-> |Z| -> |m2| -> r0
        #
        # X = dp1 | Id_D
        # Z = Id_B1 | dp2

        #      ___
        #     |   |------------------------->A
        #     |   |          |-B1----------->
        # f1->|   |--B1----->|         ___
        #     | 1 |          |----B2->|   |
        #     |___| -C1-----------C2->| 2 |->r2
        # ---------D----------------->|___|

        #      ___
        #     |   |-------------------------------->A
        #     |   |  .            *-B1-------.----->
        # f1->|   |  . |--B1----->*          .   ___
        #     | 1 |--.-|          *----B2->| .  |   |
        #     |___|  . |-C1------------C2->|-.->| 2 |->r2
        # ---------D-.-------------------->| .  |___|
        # m1  | X | Y                        |  Z    | m2

        # I need to write the muxer
        # look at the end
        # iterate 2's functions

        Y_coords_A_B1 = []
        for x in A:
            Y_coords_A_B1.append((0, r1.index(x)))
        for x in B1:
            Y_coords_A_B1.append((0, r1.index(x)))

        Y_coords_B2_C2_D = []
        for x in f2:
            if (x in B2) or (x in C2):
                Y_coords_B2_C2_D.append((0, r1.index(s1_from_s2(x))))
                assert x not in D
            elif x in D:
                Y_coords_B2_C2_D.append((1, D.index(x)))
            else:
                assert False

        # print ('Y_coords_A_B1: %s' % Y_coords_A_B1)
        # print ('Y_coords_B2_C2_D: %s' % Y_coords_B2_C2_D)
        Y_coords = [Y_coords_A_B1, Y_coords_B2_C2_D]
        Y = Mux(m1_X.get_res_space(), Y_coords)

        # m1* Xp Y* Zp m2*
        # Let's make series
        # m1_X is simplifed
        Y_Z = make_series(Y, Z)
        Y_Z_m2 = make_series(Y_Z, m2)

        res_dp = make_series(m1_X, Y_Z_m2)

        fnames = fntot
        rnames = rntot

        res_dp, fnames, rnames = simplify_if_only_one_name(
            res_dp, fnames, rnames)

        # print('res_dp: %s' % res_dp)
        res = dpwrap(res_dp, fnames, rnames)

        return res

    except Exception as e:
        msg = 'connect2() failed'
        raise_wrapped(DPInternalError,
                      e,
                      msg,
                      ndp1=ndp1,
                      ndp2=ndp2,
                      connections=connections,
                      split=split)
Example #31
0
def check_products1():
    def check_product(S1, S2, expected):
        S, pack, unpack = get_product_compact(S1, S2)
        print('product(%s, %s) = %s  expected %s' % (S1, S2, S, expected))
        assert_equal(S, expected)

        a = S1.witness()
        b = S2.witness()
        S1.belongs(a)
        S2.belongs(b)
        c = pack(a, b)
        a2, b2 = unpack(c)
        S1.check_equal(a, a2)
        S2.check_equal(b, b2)

        print('a = %s  b = %s' % (a, b))
        print('c = %s ' % S.format(c))
        print('a2 = %s  b2 = %s' % (a2, b2))

    R = Rcomp()
    E = R_Weight
    check_product(PosetProduct((R, E)), R, PosetProduct((R, E, R)))
    check_product(PosetProduct((R, R)), E, PosetProduct((R, R, E)))
    check_product(PosetProduct((R, E)), PosetProduct((R, E)),
                  PosetProduct((R, E, R, E)))

    check_product(PosetProduct(()), R, R)
    check_product(PosetProduct(()), PosetProduct((R, )), R)
    check_product(R, PosetProduct(()), R)
    check_product(PosetProduct((R, )), PosetProduct(()), R)
Example #32
0
 def get_rtypes(self, signals):
     # Returns the product space
     types = [self.get_rtype(s) for s in signals]
     return PosetProduct(tuple(types))
Example #33
0
    def __init__(self):
        F = Single("navigate")
        R = PosetProduct((R_Power, R_Time))

        M = R_Power
        PrimitiveDP.__init__(self, F=F, R=R, M=M)
Example #34
0
    def __init__(self):
        F = PosetProduct(())
        R = PosetProduct((R_Power, R_Time))

        M = R_Power
        PrimitiveDP.__init__(self, F=F, R=R, M=M)
Example #35
0
def eval_space_spaceproduct(r, context):
    ops = get_odd_ops(unwrap_list(r.ops))
    Ss = [eval_space(_, context) for _ in ops]
    return PosetProduct(tuple(Ss))