コード例 #1
0
def get_samples(request, ndp):
    xaxis = str(request.params['xaxis'])
    # yaxis = str(request.params['yaxis'])
    xmin = request.params['xmin'].encode('utf-8')
    xmax = request.params['xmax'].encode('utf-8')
    nsamples = int(request.params['nsamples'])

    fnames = ndp.get_fnames()
    rnames = ndp.get_rnames()

    # must pass the other functions as parameters
    f = {}
    for fn in fnames:
        if fn == xaxis: continue
        if not fn in request.params:
            msg = 'You have to pass the value of function %r.' % fn
            raise_desc(ValueError, msg, rnames=rnames)

        s = request.params[fn]
        try:
            val = parse_constant(s)
        except DPSyntaxError as e:
            msg = 'Cannot parse value for %r.' % fn
            raise_wrapped(ValueError, e, msg, compact=True)

        F = ndp.get_ftype(fn)
        f[fn] = express_value_in_isomorphic_space(val.unit, val.value, F)

    F = ndp.get_ftype(xaxis)
    try:
        xmin = parse_constant(xmin)
        xmax = parse_constant(xmax)
    except DPSyntaxError as e:
        msg = 'Cannot parse value for xmax/xmin.'
        raise_wrapped(ValueError, e, msg, compact=True)

    xmin = express_value_in_isomorphic_space(xmin.unit, xmin.value, F)
    xmax = express_value_in_isomorphic_space(xmax.unit, xmax.value, F)

    xsamples = np.linspace(xmin, xmax, nsamples)
    samples = []
    for xsample in xsamples:
        t = []
        for fn in fnames:
            if fn == xaxis:
                t.append(xsample)
            else:
                t.append(f[fn])
        sample = tuple(t)
        if len(fnames) == 1:
            sample = sample[0]

        samples.append(sample)

    return samples
コード例 #2
0
def get(matches, used, Ps, get_P, Pa, ua):
    others = list(set(used) - set(matches))
    extra = PosetProduct(tuple(map(get_P, others)))
    print('extra for Pa: %s' % extra)
    Pa_comp = PosetProduct(Pa.subs + extra.subs)
    print('Pa_comp: %s' % Pa_comp)
    extra_minimals = extra.get_minimal_elements()
    m_matches = matches + others
    s = set()
    R = set()
    for m1, m2 in itertools.product(ua.minimals, extra_minimals):
        m = m1 + m2
        s.add(m)
        r = [None] * len(used)
        for i, a in enumerate(used):
            S1 = Pa_comp.subs[m_matches.index(a)]
            s1 = m[m_matches.index(a)]
            S2 = get_P(a)
            r[i] = express_value_in_isomorphic_space(S1, s1, S2)
        r = tuple(r)
        R.add(r)
    Pa_comp_lb = Pa_comp.Us(s)
    print('Pa_comp_lb: %s' % Pa_comp_lb)
    Ps_a = Ps.Us(R)
    return Ps_a
コード例 #3
0
ファイル: misc_math.py プロジェクト: rusi/mcdp
def generic_mult_constantsN(seq):
    """ Multiplies a sequence of constants that could be either Nat, Rcomp, or RCompUnits """
    for c in seq:
        if isinstance(c.unit, RbicompUnits):
            assert c.value < 0
            msg = 'Cannot multiply by negative number %s.' % c
            raise_desc(DPSemanticError, msg)

    posets = [_.unit for _ in seq]
    for p in posets:
        check_isinstance(p, (Nat, Rcomp, RcompUnits))

    promoted, R = generic_mult_table(posets)

    if isinstance(R, Nat):
        values = [_.value for _ in seq]
        from functools import reduce
        res = reduce(Nat_mult_uppersets_continuous, values)
        return ValueWithUnits(res, R)
    else:
        res = 1.0
        for vu, F2 in zip(seq, promoted):
            value2 = express_value_in_isomorphic_space(vu.unit, vu.value, F2)
            if F2.equal(value2, F2.get_top()):
                res = R.get_top()
                break
            res *= value2
        return ValueWithUnits(res, R)
        # XXX needs to check overflow
    return res
コード例 #4
0
def eval_rvalue_approx_step(r, context):
    assert isinstance(r, CDP.ApproxStepRes)

    resource = eval_rvalue(r.rvalue, context)
    step = eval_constant(r.step, context)
    
    R = context.get_rtype(resource)
    tu = get_types_universe()
    try:
        tu.check_leq(step.unit, R)
    except NotLeq:
        msg = ('The step is specified in a unit (%s), which is not compatible '
               'with the resource (%s).' % (step.unit, R))
        raise_desc(DPSemanticError, msg)

    stepu = express_value_in_isomorphic_space(S1=step.unit, s1=step.value, S2=R)

    if not isinstance(R, (RcompUnits)):
        msg = 'approx() not implemented for %s.'%R
        raise_desc(DPNotImplementedError, msg)
        
    dp = makeLinearCeilDP(R, stepu)

    return create_operation(context, dp=dp, resources=[resource],
                               name_prefix='_approx', op_prefix='_toapprox',
                                res_prefix='_result')
コード例 #5
0
def eval_rvalue_approx_step(r, context):
    assert isinstance(r, CDP.ApproxStepRes)

    resource = eval_rvalue(r.rvalue, context)
    step = eval_constant(r.step, context)
    
    R = context.get_rtype(resource)
    tu = get_types_universe()
    try:
        tu.check_leq(step.unit, R)
    except NotLeq:
        msg = ('The step is specified in a unit (%s), which is not compatible '
               'with the resource (%s).' % (step.unit, R))
        raise_desc(DPSemanticError, msg)

    stepu = express_value_in_isomorphic_space(S1=step.unit, s1=step.value, S2=R)

    if not isinstance(R, (RcompUnits)):
        msg = 'approx() not implemented for %s.'%R
        raise_desc(DPNotImplementedError, msg)
        
    dp = makeLinearCeilDP(R, stepu)

    return create_operation(context, dp=dp, resources=[resource],
                               name_prefix='_approx', op_prefix='_toapprox',
                                res_prefix='_result')
コード例 #6
0
ファイル: misc_math.py プロジェクト: AndreaCensi/mcdp
def generic_mult_constantsN(seq):
    """ Multiplies a sequence of constants that could be either Nat, Rcomp, or RCompUnits """
    for c in seq:
        if isinstance(c.unit, RbicompUnits):
            assert c.value < 0
            msg = "Cannot multiply by negative number %s." % c
            raise_desc(DPSemanticError, msg)

    posets = [_.unit for _ in seq]
    for p in posets:
        check_isinstance(p, (Nat, Rcomp, RcompUnits))

    promoted, R = generic_mult_table(posets)

    if isinstance(R, Nat):
        values = [_.value for _ in seq]
        from functools import reduce

        res = reduce(Nat_mult_uppersets_continuous, values)
        return ValueWithUnits(res, R)
    else:
        res = 1.0
        for vu, F2 in zip(seq, promoted):
            value2 = express_value_in_isomorphic_space(vu.unit, vu.value, F2)
            if F2.equal(value2, F2.get_top()):
                res = R.get_top()
                break
            res *= value2
        return ValueWithUnits(res, R)
        # XXX needs to check overflow
    return res
コード例 #7
0
ファイル: eval_math.py プロジェクト: rusi/mcdp
def x_minus_constants(x, constants):
    R0 = x.unit

    if not isinstance(R0, RcompUnits):
        msg = 'Cannot evaluate "-" on this space.'
        raise_desc(DPSemanticError, msg, R0=R0)

    Rb = RbicompUnits.from_rcompunits(R0)

    # convert each factor to R0
    try:
        v0 = x.value
        for c in constants:
            vi = express_value_in_isomorphic_space(c.unit, c.value, Rb)
            v0 = RbicompUnits_subtract(Rb, v0, vi)
    except TypeError as e:
        msg = 'Failure to compute subtraction.'
        raise_wrapped(DPInternalError, e, msg, x=x, constants=constants)

    if Rb.leq(0.0, v0):
        R1 = R0
    else:
        R1 = Rb

    return ValueWithUnits(unit=R1, value=v0)
コード例 #8
0
ファイル: eval_math.py プロジェクト: AndreaCensi/mcdp
def x_minus_constants(x, constants):
    R0 = x.unit
    
    if not isinstance(R0, RcompUnits):
        msg = 'Cannot evaluate "-" on this space.'
        raise_desc(DPSemanticError, msg, R0=R0)

    Rb = RbicompUnits.from_rcompunits(R0)
    
    # convert each factor to R0
    try:
        v0 = x.value
        for c in constants:
            vi = express_value_in_isomorphic_space(c.unit, c.value, Rb)
            v0 = RbicompUnits_subtract(Rb, v0, vi)
    except TypeError as e:
        msg = 'Failure to compute subtraction.'
        raise_wrapped(DPInternalError, e, msg, x=x, constants=constants)
    
    if Rb.leq(0.0, v0):
        R1 = R0
    else:
        R1 = Rb
        
    return ValueWithUnits(unit=R1, value=v0)
コード例 #9
0
ファイル: plus_value_map.py プロジェクト: rusi/mcdp
 def __init__(self, P, c_value, c_space):
     c_space.belongs(c_value)
     check_isinstance(P, RcompUnits)
     check_isinstance(c_space, RcompUnits)
     self.c_value = c_value
     self.c_space = c_space
     self.c = express_value_in_isomorphic_space(c_space, c_value, P)
     Map.__init__(self, dom=P, cod=P)
コード例 #10
0
ファイル: coproducts.py プロジェクト: rusi/mcdp
def check_coproduct_embedding1():
    A = FinitePoset(set(['a1', 'a2', 'a3']), [])
    B = FinitePoset(set(['b1', 'b2']), [])

    P = PosetCoproduct((A, B))

    a = 'a1'
    A.belongs(a)
    p = express_value_in_isomorphic_space(A, a, P)

    # a2 = express_value_in_isomorphic_space(P, p, A)
    # A.belongs(a2)

    print p
コード例 #11
0
ファイル: utils2.py プロジェクト: AndreaCensi/mcdp
def eval_rvalue_as_constant_same(s1, s2):
    """ 
        Checks that the two strings evaluate to the same constant.
        (up to conversions)
        
        Example:
            
            eval_rvalue_as_constant_same("1 g + 1 kg", "1001 g")
            
    """

    p1 = eval_rvalue_as_constant2(s1)
    p2 = eval_rvalue_as_constant2(s2)

    v2 = express_value_in_isomorphic_space(p2.unit, p2.value, p1.unit)

    p1.unit.check_equal(p1.value, v2)
コード例 #12
0
def eval_rvalue_as_constant_same(s1, s2):
    """ 
        Checks that the two strings evaluate to the same constant.
        (up to conversions)
        
        Example:
            
            eval_rvalue_as_constant_same("1 g + 1 kg", "1001 g")
            
    """

    p1 = eval_rvalue_as_constant2(s1)
    p2 = eval_rvalue_as_constant2(s2)

    v2 = express_value_in_isomorphic_space(p2.unit, p2.value, p1.unit)

    p1.unit.check_equal(p1.value, v2)
コード例 #13
0
def assert_generic(r, context, which):
    """ a : v1 < v2
        b : v1 = v2
        b : v1 = v2
    """
    from .eval_constant_imp import eval_constant

    v1 = eval_constant(r.v1, context)
    v2 = eval_constant(r.v2, context)
    
    # put v2 in v1's space
    P = v1.unit
    value1 = v1.value
    tu = get_types_universe()
    
    try:
        tu.check_leq(v2.unit, v1.unit)
    except NotLeq as e:
        msg = 'Cannot cast %s to %s.' % (v2.unit, v1.unit)
        raise_wrapped(DPSemanticError, e, msg, compact=True)
    value2 = express_value_in_isomorphic_space(v2.unit, v2.value, v1.unit)
    
    t = {}
    t['equal'] = P.equal(value1, value2)
    t['leq'] = P.leq(value1, value2)
    t['geq'] = P.leq(value2, value1)
    t['lt'] = t['leq'] and not t['equal']
    t['gt'] = t['geq'] and not t['equal']
     
    if not which in t:
        raise ValueError(t)
    
    result = t[which]
    if result:
        return passed_value()
    
    else: # assertion
        msg = 'Assertion %r failed.' % which
        raise_desc(DPUserAssertion, msg, expected=v1, obtained=v2)
コード例 #14
0
def assert_generic(r, context, which):
    """ a : v1 < v2
        b : v1 = v2
        b : v1 = v2
    """
    from .eval_constant_imp import eval_constant

    v1 = eval_constant(r.v1, context)
    v2 = eval_constant(r.v2, context)
    
    # put v2 in v1's space
    P = v1.unit
    value1 = v1.value
    tu = get_types_universe()
    
    try:
        tu.check_leq(v2.unit, v1.unit)
    except NotLeq as e:
        msg = 'Cannot cast %s to %s.' % (v2.unit, v1.unit)
        raise_wrapped(DPSemanticError, e, msg, compact=True)
    value2 = express_value_in_isomorphic_space(v2.unit, v2.value, v1.unit)
    
    t = {}
    t['equal'] = P.equal(value1, value2)
    t['leq'] = P.leq(value1, value2)
    t['geq'] = P.leq(value2, value1)
    t['lt'] = t['leq'] and not t['equal']
    t['gt'] = t['geq'] and not t['equal']
     
    if not which in t:
        raise ValueError(t)
    
    result = t[which]
    if result:
        return passed_value()
    
    else: # assertion
        msg = 'Assertion %r failed.' % which
        raise_desc(DPUserAssertion, msg, expected=v1, obtained=v2)
コード例 #15
0
 def cast_value(self, P):
     """ Returns the value cast in the space P (larger than
         the current space). """
     return express_value_in_isomorphic_space(self.unit, self.value, P)
コード例 #16
0
ファイル: solve_meat.py プロジェクト: AndreaCensi/mcdp
def solve_main(
    logger,
    config_dirs,
    maindir,
    cache_dir,
    model_name,
    lower,
    upper,
    out_dir,
    max_steps,
    query_strings,
    intervals,
    _exp_advanced,
    expect_nres,
    imp,
    expect_nimp,
    plot,
    do_movie,
    # expect_res=None,
    expect_res,  # @UnusedVariable
    make,
):

    if out_dir is None:
        out = solve_get_output_dir(prefix="out/out")
    else:
        out = out_dir

    logger.info("Using output dir %r" % out)

    librarian = Librarian()
    logger.info("Looking for libraries in %s..." % config_dirs)
    for e in config_dirs:
        librarian.find_libraries(e)
    logger.info("Found %d libraries." % len(librarian.get_libraries()))

    library = librarian.get_library_by_dir(maindir)
    if cache_dir is not None:
        library.use_cache_dir(cache_dir)

    ndp = library.load_ndp(model_name)
    basename = model_name

    if make or (plot and imp):
        ndp_labelled = get_labelled_version(ndp)
    else:
        ndp_labelled = ndp

    basename, dp = solve_get_dp_from_ndp(basename=basename, ndp=ndp_labelled, lower=lower, upper=upper)

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

    query = " ".join(query_strings)
    c = library.parse_constant(query)
    tu = get_types_universe()
    try:
        tu.check_leq(c.unit, F)
    except NotLeq as e:
        msg = "The value given cannot be converted to functionality space."
        raise_wrapped(UserError, e, msg, unit=c.unit, F=F, compact=True)
    fg = express_value_in_isomorphic_space(c.unit, c.value, F)

    logger.info("query: %s" % F.format(fg))

    tracer = Tracer(logger=logger)
    res, trace = solve_meat_solve(tracer, ndp, dp, fg, intervals, max_steps, _exp_advanced)

    nres = len(res.minimals)

    if expect_nres is not None:
        if nres != expect_nres:
            msg = "Found wrong number of resources"
            raise_desc(ExpectationsNotMet, msg, expect_nres=expect_nres, nres=nres)

    if imp:
        M = dp.get_imp_space()
        nimplementations = 0
        for r in res.minimals:
            ms = dp.get_implementations_f_r(fg, r)
            nimplementations += len(ms)
            s = "r = %s " % R.format(r)
            for j, m in enumerate(ms):
                # print('m = %s' % str(m))
                s += "\n  implementation %d of %d: m = %s " % (j + 1, len(ms), M.format(m))

                if make:
                    imp_dict = get_imp_as_recursive_dict(M, m)  # , ignore_hidden=False)
                    print("imp dict: %r" % imp_dict)
                    context = {}
                    artifact = ndp_make(ndp, imp_dict, context)

                    print("artifact: %s" % artifact)

            tracer.log(s)

        if expect_nimp is not None:
            if expect_nimp != nimplementations:
                msg = "Found wrong number of implementations"
                raise_desc(ExpectationsNotMet, msg, expect_nimp=expect_nimp, nimplementations=nimplementations)

    #     if expect_res is not None:
    #         value = interpret_string(expect_res)
    #         tracer.log('value: %s' % value)
    #         res_expected = value.value
    #         tu = get_types_universe()
    #         # If it's a tuple of two elements, then we assume it's upper/lower bounds
    #         if isinstance(value.unit, PosetProduct):
    #             subs = value.unit.subs
    #             assert len(subs) == 2, subs
    #
    #             lower_UR_expected, upper_UR_expected = subs
    #             lower_res_expected, upper_res_expected = value.value
    #
    #             lower_bound = tu.get_embedding(lower_UR_expected, UR)[0](lower_res_expected)
    #             upper_bound = tu.get_embedding(upper_UR_expected, UR)[0](upper_res_expected)
    #
    #             tracer.log('lower: %s <= %s' % (UR.format(lower_bound), UR.format(res)))
    #             tracer.log('upper: %s <= %s' % (UR.format(upper_bound), UR.format(res)))
    #
    #             UR.check_leq(lower_bound, res)
    #             UR.check_leq(res, upper_bound)
    #         else:
    #             # only one element: equality
    #             UR_expected = value.unit
    #             tu.check_leq(UR_expected, UR)
    #             A_to_B, _B_to_A = tu.get_embedding(UR_expected, UR)
    #
    #             res_expected_f = A_to_B(res_expected)
    #             try:
    #                 UR.check_equal(res, res_expected_f)
    #             except NotEqual as e:
    #                 raise_wrapped(ExpectationsNotMet, e, 'res is different',
    #                               res=res, res_expected=res_expected, compact=True)

    if plot:
        r = Report()
        if _exp_advanced:
            from mcdp_report.generic_report_utils import generic_report

            generic_report(r, dp, trace, annotation=None, axis0=(0, 0, 0, 0))
        else:
            f = r.figure()
            from mcdp_report.generic_report_utils import generic_plot

            generic_plot(f, space=UR, value=res)
            from mcdp_report.generic_report_utils import generic_report_trace

            generic_report_trace(r, ndp, dp, trace, out, do_movie=do_movie)

        out_html = os.path.join(out, "report.html")
        logger.info("writing to %r" % out_html)
        r.to_html(out_html)

    if plot and imp:
        from mcdp_report_ndp_tests.test1 import GetValues
        from mcdp_report.gg_ndp import gvgen_from_ndp
        from mcdp_report.gdc import STYLE_GREENREDSYM
        from mcdp_report.gg_utils import gg_figure

        M = dp.get_imp_space()

        report_solutions = Report()
        for i, r in enumerate(res.minimals):
            ms = dp.get_implementations_f_r(fg, r)
            for j, m in enumerate(ms):

                imp_dict = get_imp_as_recursive_dict(M, m)
                images_paths = library.get_images_paths()
                gv = GetValues(ndp=ndp, imp_dict=imp_dict, nu=upper, nl=1)

                setattr(ndp, "_hack_force_enclose", True)

                with report_solutions.subsection("sol-%s-%s" % (i, j)) as rr:
                    # Left right
                    gg = gvgen_from_ndp(
                        ndp=ndp, style=STYLE_GREENREDSYM, images_paths=images_paths, plotting_info=gv, direction="LR"
                    )

                    gg_figure(rr, "figure", gg, do_png=True, do_pdf=True, do_svg=False, do_dot=False)

                    # Top-bottom
                    gg = gvgen_from_ndp(
                        ndp=ndp, style=STYLE_GREENREDSYM, images_paths=images_paths, plotting_info=gv, direction="TB"
                    )

                    gg_figure(rr, "figure2", gg, do_png=True, do_pdf=True, do_svg=False, do_dot=False)

        out_html = os.path.join(out, "report_solutions.html")
        logger.info("writing to %r" % out_html)
        report_solutions.to_html(out_html)
コード例 #17
0
ファイル: loading.py プロジェクト: AndreaCensi/mcdp
def friendly_solve(ndp, query, result_like='dict(str:str)', upper=None, lower=None):
    """
        query = dict(power=(100,"W"))
        result_like = dict(power="W")
        
        s = solve
    
    """
    #print('friendly_solve(upper=%s, lower=%s)' % (upper, lower))
    # TODO: replace with convert_string_query(ndp, query, context):
    fnames = ndp.get_fnames()
    rnames = ndp.get_rnames()

    if not len(rnames) >= 1:
        raise NotImplementedError()
    
    value = []

    for fname in fnames:
        if not fname in query:
            msg = 'Missing function'
            raise_desc(ValueError, msg, fname=fname, query=query, fnames=fnames)

        F = ndp.get_ftype(fname)
        q, qs = query[fname]
        s = '%s %s' % (q, qs)

        try:
            val = interpret_params_1string(s, F=F)
        except NotLeq as e:
            raise_wrapped(ValueError, e, 'wrong type', fname=fname)
            
        value.append(val)

    if len(fnames) == 1:
        value = value[0]
    else:
        value = tuple(value)

    if hasattr(ndp, '_cache_dp0'):
        dp0 = ndp._cache_dp0
    else:
        
        dp0 = ndp.get_dp()
        ndp._cache_dp0 = dp0
        
    if upper is not None:
        _, dp = get_dp_bounds(dp0, nl=1, nu=upper)

    elif lower is not None:
        dp, _ = get_dp_bounds(dp0, nl=lower, nu=1)
    else:
        dp = dp0
        
    F = dp.get_fun_space()
    F.belongs(value)

    from mocdp import logger
    trace = Tracer(logger=logger)
    res = dp.solve_trace(value, trace)
    R = dp.get_res_space()
    UR = UpperSets(R)
    print('value: %s' % F.format(value))
    print('results: %s' % UR.format(res))

    ares = []
    implementations = []

    for r in res.minimals:
        rnames = ndp.get_rnames()
        fr = dict()
        for rname, sunit in result_like.items():
            if not rname in rnames:
                msg = 'Could not find resource %r.' % rname
                raise_desc(ValueError, msg, rnames=rnames)
            i = rnames.index(rname)
            unit = interpret_string_as_space(sunit)
            Ri = ndp.get_rtype(rname)
            if len(rnames) > 1:
                ri = r[i]
            else:
                assert i == 0
                ri = r
            v = express_value_in_isomorphic_space(S1=Ri, s1=ri, S2=unit)
            fr[rname] = v
        
        ares.append(fr)
        
        ms = dp.get_implementations_f_r(value, r)
        implementations.append(ms)
        
    return ares, implementations
コード例 #18
0
ファイル: optimization.py プロジェクト: rusi/mcdp
    def __init__(self, library, options,
                 flabels, F0s, f0s,
                 rlabels, R0s, r0s, initial):

        f0s = list(f0s)
        F0s = list(F0s)
        r0s = list(r0s)
        R0s = list(R0s)

        for i, (fname, F0, f0) in enumerate(zip(flabels, F0s, f0s)):
            F0.belongs(f0)
            F = initial.get_ftype(fname)
            f0s[i] = express_value_in_isomorphic_space(F0, f0, F)
            F0s[i] = F

        for i, (rname, R0, r0) in enumerate(zip(rlabels, R0s, r0s)):
            R0.belongs(r0)
            R = initial.get_rtype(rname)
            r0s[i] = express_value_in_isomorphic_space(R0, r0, R)
            R0s[i] = R

        self.library = library
        self.options = options
        self.flabels = flabels
        self.rlabels = rlabels
        self.F0s = F0s
        self.R0s = R0s
        self.r0s = r0s
        self.f0s = f0s
        
        context = create_context0(flabels, F0s, f0s, rlabels, R0s, r0s, initial=initial)

        from mcdp_opt.optimization_state import OptimizationState

        unconnected = []
        for o in options:
            ndp = library.load_ndp(o)
            try:
                ndp.check_fully_connected()
            except NotConnected as e:
                if o.lower() == "raspberrypi2":
                    # 
                    pass
                unconnected.append(o)


        for u in unconnected:
            options.remove(u)

        print('Removing the unusable options %s' % sorted(unconnected))
        print('Remaining with %s' % sorted(options))

        lower_bounds = {}
        for fname, F0, f0 in zip(flabels, F0s, f0s):
            r = CResource(get_name_for_fun_node(fname), fname)
            lower_bounds[r] = F0.U(f0)
        from mcdp_opt.partial_result import get_lower_bound_ndp
        ndp, table = get_lower_bound_ndp(context)
        (_R, ur), _tableres = self.get_lower_bounds(ndp, table)

        self.num_created = 0
        s0 = OptimizationState(self, options, context, executed=[], forbidden=set(),
                               lower_bounds=lower_bounds, ur=ur,
                               creation_order=self.get_next_creation())

        self.root = s0
        # open nodes
        self.states = [s0]
        self.actions = [(s0, ActionExpand())]  # tuples of state, action
        
        # connected
        self.done = []
        # impossible
        self.abandoned = []
        # expanded
        self.expanded = []

        # extra ndps not present in library
        self.additional = {}  # str -> NamedDP

        self.iteration = 0

        # for visualization
        self.G = nx.DiGraph()
        self.G_dom = nx.DiGraph()  # domination graph
コード例 #19
0
ファイル: loading.py プロジェクト: rusi/mcdp
def friendly_solve(ndp, query, result_like='dict(str:str)', upper=None, lower=None):
    """
        query = dict(power=(100,"W"))
        result_like = dict(power="W")
        
        s = solve
    
    """
    #print('friendly_solve(upper=%s, lower=%s)' % (upper, lower))
    # TODO: replace with convert_string_query(ndp, query, context):
    fnames = ndp.get_fnames()
    rnames = ndp.get_rnames()

    if not len(rnames) >= 1:
        raise NotImplementedError()
    
    value = []

    for fname in fnames:
        if not fname in query:
            msg = 'Missing function'
            raise_desc(ValueError, msg, fname=fname, query=query, fnames=fnames)

        F = ndp.get_ftype(fname)
        q, qs = query[fname]
        s = '%s %s' % (q, qs)

        try:
            val = interpret_params_1string(s, F=F)
        except NotLeq as e:
            raise_wrapped(ValueError, e, 'wrong type', fname=fname)
            
        value.append(val)

    if len(fnames) == 1:
        value = value[0]
    else:
        value = tuple(value)

    if hasattr(ndp, '_cache_dp0'):
        dp0 = ndp._cache_dp0
    else:
        
        dp0 = ndp.get_dp()
        ndp._cache_dp0 = dp0
        
    if upper is not None:
        _, dp = get_dp_bounds(dp0, nl=1, nu=upper)

    elif lower is not None:
        dp, _ = get_dp_bounds(dp0, nl=lower, nu=1)
    else:
        dp = dp0
        
    F = dp.get_fun_space()
    F.belongs(value)

    from mcdp import logger
    trace = Tracer(logger=logger)
    res = dp.solve_trace(value, trace)
    R = dp.get_res_space()
    UR = UpperSets(R)
    print('value: %s' % F.format(value))
    print('results: %s' % UR.format(res))

    ares = []
    implementations = []

    for r in res.minimals:
        rnames = ndp.get_rnames()
        fr = dict()
        for rname, sunit in result_like.items():
            if not rname in rnames:
                msg = 'Could not find resource %r.' % rname
                raise_desc(ValueError, msg, rnames=rnames)
            i = rnames.index(rname)
            unit = interpret_string_as_space(sunit)
            Ri = ndp.get_rtype(rname)
            if len(rnames) > 1:
                ri = r[i]
            else:
                assert i == 0
                ri = r
            v = express_value_in_isomorphic_space(S1=Ri, s1=ri, S2=unit)
            fr[rname] = v
        
        ares.append(fr)
        
        ms = dp.get_implementations_f_r(value, r)
        implementations.append(ms)
        
    return ares, implementations
コード例 #20
0
def solve_main(
        logger,
        config_dirs,
        maindir,
        cache_dir,
        model_name,
        lower,
        upper,
        out_dir,
        max_steps,
        query_strings,
        intervals,
        _exp_advanced,
        expect_nres,
        imp,
        expect_nimp,
        plot,
        do_movie,

        # expect_res=None,
        expect_res,  # @UnusedVariable
        make):

    if out_dir is None:
        out = solve_get_output_dir(prefix='out/out')
    else:
        out = out_dir

    logger.info('Using output dir %r' % out)

    librarian = Librarian()
    logger.info('Looking for libraries in %s...' % config_dirs)
    for e in config_dirs:
        librarian.find_libraries(e)
    logger.info('Found %d libraries.' % len(librarian.get_libraries()))

    library = librarian.get_library_by_dir(maindir)
    if cache_dir is not None:
        library.use_cache_dir(cache_dir)

    ndp = library.load_ndp(model_name)
    basename = model_name

    if make or (plot and imp):
        ndp_labelled = get_labelled_version(ndp)
    else:
        ndp_labelled = ndp

    basename, dp = solve_get_dp_from_ndp(basename=basename,
                                         ndp=ndp_labelled,
                                         lower=lower,
                                         upper=upper)

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

    query = " ".join(query_strings)
    c = library.parse_constant(query)
    tu = get_types_universe()
    try:
        tu.check_leq(c.unit, F)
    except NotLeq as e:
        msg = 'The value given cannot be converted to functionality space.'
        raise_wrapped(UserError, e, msg, unit=c.unit, F=F, compact=True)
    fg = express_value_in_isomorphic_space(c.unit, c.value, F)

    logger.info('query: %s' % F.format(fg))

    tracer = Tracer(logger=logger)
    res, trace = solve_meat_solve_ftor(tracer, ndp, dp, fg, intervals,
                                       max_steps, _exp_advanced)

    nres = len(res.minimals)

    if expect_nres is not None:
        if nres != expect_nres:
            msg = 'Found wrong number of resources'
            raise_desc(ExpectationsNotMet,
                       msg,
                       expect_nres=expect_nres,
                       nres=nres)

    if imp:
        M = dp.get_imp_space()
        nimplementations = 0
        for r in res.minimals:
            ms = dp.get_implementations_f_r(fg, r)
            nimplementations += len(ms)
            s = 'r = %s ' % R.format(r)
            for j, m in enumerate(ms):
                # print('m = %s' % str(m))
                s += "\n  implementation %d of %d: m = %s " % (j + 1, len(ms),
                                                               M.format(m))

                if make:
                    imp_dict = get_imp_as_recursive_dict(
                        M, m)  # , ignore_hidden=False)
                    print('imp dict: %r' % imp_dict)
                    context = {}
                    artifact = ndp_make(ndp, imp_dict, context)

                    print('artifact: %s' % artifact)

            tracer.log(s)

        if expect_nimp is not None:
            if expect_nimp != nimplementations:
                msg = 'Found wrong number of implementations'
                raise_desc(ExpectationsNotMet,
                           msg,
                           expect_nimp=expect_nimp,
                           nimplementations=nimplementations)


#     if expect_res is not None:
#         value = interpret_string(expect_res)
#         tracer.log('value: %s' % value)
#         res_expected = value.value
#         tu = get_types_universe()
#         # If it's a tuple of two elements, then we assume it's upper/lower bounds
#         if isinstance(value.unit, PosetProduct):
#             subs = value.unit.subs
#             assert len(subs) == 2, subs
#
#             lower_UR_expected, upper_UR_expected = subs
#             lower_res_expected, upper_res_expected = value.value
#
#             lower_bound = tu.get_embedding(lower_UR_expected, UR)[0](lower_res_expected)
#             upper_bound = tu.get_embedding(upper_UR_expected, UR)[0](upper_res_expected)
#
#             tracer.log('lower: %s <= %s' % (UR.format(lower_bound), UR.format(res)))
#             tracer.log('upper: %s <= %s' % (UR.format(upper_bound), UR.format(res)))
#
#             UR.check_leq(lower_bound, res)
#             UR.check_leq(res, upper_bound)
#         else:
#             # only one element: equality
#             UR_expected = value.unit
#             tu.check_leq(UR_expected, UR)
#             A_to_B, _B_to_A = tu.get_embedding(UR_expected, UR)
#
#             res_expected_f = A_to_B(res_expected)
#             try:
#                 UR.check_equal(res, res_expected_f)
#             except NotEqual as e:
#                 raise_wrapped(ExpectationsNotMet, e, 'res is different',
#                               res=res, res_expected=res_expected, compact=True)

    if plot:
        r = Report()
        if _exp_advanced:
            from mcdp_report.generic_report_utils import generic_report
            generic_report(r, dp, trace, annotation=None, axis0=(0, 0, 0, 0))
        else:
            f = r.figure()
            from mcdp_report.generic_report_utils import generic_plot
            generic_plot(f, space=UR, value=res)
            from mcdp_report.generic_report_utils import generic_report_trace
            generic_report_trace(r, ndp, dp, trace, out, do_movie=do_movie)

        out_html = os.path.join(out, 'report.html')
        logger.info('writing to %r' % out_html)
        r.to_html(out_html)

    if plot and imp:
        from mcdp_report_ndp_tests.test1 import GetValues
        from mcdp_report.gg_ndp import gvgen_from_ndp
        from mcdp_report.gdc import STYLE_GREENREDSYM
        from mcdp_report.gg_utils import gg_figure
        M = dp.get_imp_space()

        report_solutions = Report()
        for i, r in enumerate(res.minimals):
            ms = dp.get_implementations_f_r(fg, r)
            for j, m in enumerate(ms):

                imp_dict = get_imp_as_recursive_dict(M, m)
                images_paths = library.get_images_paths()
                image_source = ImagesFromPaths(images_paths)
                gv = GetValues(ndp=ndp, imp_dict=imp_dict, nu=upper, nl=1)

                setattr(ndp, '_hack_force_enclose', True)

                with report_solutions.subsection('sol-%s-%s' % (i, j)) as rr:
                    # Left right
                    gg = gvgen_from_ndp(ndp=ndp,
                                        style=STYLE_GREENREDSYM,
                                        image_source=image_source,
                                        plotting_info=gv,
                                        direction='LR')

                    gg_figure(rr,
                              'figure',
                              gg,
                              do_png=True,
                              do_pdf=True,
                              do_svg=False,
                              do_dot=False)

                    # Top-bottom
                    gg = gvgen_from_ndp(ndp=ndp,
                                        style=STYLE_GREENREDSYM,
                                        image_source=image_source,
                                        plotting_info=gv,
                                        direction='TB')

                    gg_figure(rr,
                              'figure2',
                              gg,
                              do_png=True,
                              do_pdf=True,
                              do_svg=False,
                              do_dot=False)

        out_html = os.path.join(out, 'report_solutions.html')
        logger.info('writing to %r' % out_html)
        report_solutions.to_html(out_html)