Пример #1
0
 def to_tensor(s):
     assert len(s) == 4
     assert s[-2:] == (None, None)
     return Tensor(
         [[[[z3.RealVal(1) / z3.RealVal(kx * ky) for i4 in range(ky)]
            for i3 in range(kx)] for i2 in range(s[1])]
          for i1 in range(s[0])])
Пример #2
0
    def translate(self, term):
        """Translate a Maude term into an SMT formula"""

        symbol = term.symbol()

        # Variable
        if str(symbol) == str(term.getSort()):
            return smt.Const(str(term), self._smt_sort(term.getSort()))
        # Integer constant
        elif symbol == self.intlit_symb:
            return smt.IntVal(int(term))
        # Real constant
        elif symbol == self.reallit_symb:
            return smt.RealVal(float(term))
        # Other symbols
        else:
            symb = self.ops_table.get(symbol)

            # If the symbol is not in the table, it may be a
            # polymorph for a custom type...
            if symb is None:
                symb = self._make_polymorph(symbol)

                # ...or an uninterpreted function
                if symb is None:
                    symb = self._make_function(symbol)

            return symb(*[self.translate(arg) for arg in term.arguments()])
Пример #3
0
def pyval2z3val(val):
    if type(val) is float:
        return z3.RealVal(val)
    elif type(val) is int:
        return z3.IntVal(val)
    else:
        raise err.Fatal('unhandled python val type!')
Пример #4
0
def _py2expr(a, ctx=None):
    if isinstance(a, bool):
        return z3.BoolVal(a, ctx)
    if isinstance(a, int):
        return z3.IntVal(a, ctx)
    if isinstance(a, float):
        return z3.RealVal(a, ctx)
Пример #5
0
def get_z3_val(valtype, value, name, datatype_name=None, ctx=None):
    val = None
    if isinstance(valtype, z3.z3.DatatypeSortRef):  # discrete values datatype
        val = getattr(valtype, value)
    elif valtype is Types.INT:
        try:
            val = z3.BitVecVal(value, 32, ctx=ctx)
        except Exception as exc:
            raise ValueError(
                f"Error during INT conversion. Cannot convert value: {value}, type: {type(value)}, name: {name}"
            )
    elif valtype is Types.INTEGER:
        try:
            val = z3.IntVal(value, ctx=ctx)
        except Exception as exc:
            raise ValueError(
                f"Error during INTEGER conversion. Cannot convert value: {value}, type: {type(value)}, name: {name}"
            )
    elif valtype is Types.FLOAT:
        try:
            val = z3.FPVal(value, z3.Float32(), ctx=ctx)
        except Exception as exc:
            raise ValueError(
                f"Error during FLOAT conversion. Cannot convert value: {value}, type: {type(value)}, name: {name}"
            )
    elif valtype is Types.REAL:
        try:
            val = z3.RealVal(value, ctx=ctx)
        except Exception as exc:
            raise ValueError(
                f"Error during REAL conversion. Cannot convert value: {value}, type: {type(value)}, name: {name}"
            )
    elif valtype is Types.BOOL:
        try:
            val = z3.BoolVal(value, ctx=ctx)
        except Exception as exc:
            raise ValueError(
                f"Error during BOOL conversion of value to INT. value: {value}, type: {type(value)}, name: {name}"
            )
    elif valtype is Types.STRING:
        try:
            val = z3.StringVal(value, ctx=ctx)
        except Exception as exc:
            raise ValueError(
                f"Error during STRING conversion of value to INT. value: {value}, type: {type(value)}, name: {name}"
            )
    elif isinstance(valtype, list):
        datatype = _get_datatype_from_list(valtype, datatype_name)
        val = getattr(datatype, value)
        valtype = datatype
    else:
        raise ValueError(
            f"I do not know how to create a z3-value for type {valtype}")

    assert val is not None, f"Value wasn't converted: valtype: {valtype}, value: {value}, name: {name}"
    val.type = valtype
    return val
Пример #6
0
    def _link_constant(self, phi):
        assert isinstance(phi, amnet.Constant)

        # *overwrite* the output variable of phi to be a z3 RealVal
        assert self.ctx.is_valid()
        name = self.ctx.name_of(phi)

        assert len(phi.b) == len(self.vars[name])  # pre-overwrite
        self.vars[name] = [z3.RealVal(bi) for bi in phi.b]
        assert self.ctx.is_valid()  # post-overwrite
Пример #7
0
 def __parse_constant__(self, symbol_node: jcmuta.SymbolNode):
     constant = symbol_node.get_content().get_token_value()
     if isinstance(constant, bool):
         return z3.BoolVal(constant)
     elif isinstance(constant, int):
         if self.bitSwitch:
             return z3.BitVecVal(constant, self.longSize)
         else:
             return z3.IntVal(constant)
     else:
         return z3.RealVal(constant)
Пример #8
0
 def trans(self, term):
     sort = type_to_data_sort(term.type)
     if isinstance(sort, z3.ArithSortRef):
         if sort.is_real():
             return z3.RealVal(term.literal)
         else:
             return z3.IntVal(term.literal)
     elif isinstance(sort, z3.BoolSortRef):
         return z3.BoolVal(term.literal)
     else:
         # TODO: Unsupported literal terms, just create fresh variable
         return self.mkVar(term.type)
Пример #9
0
def to_z3_obj(arg, typ, ident_t=None, bitlen=32):
    def intern_int(x):
        if len(x) == 3:
            return z3.BitVecVal(int(x[2], 16), bitlen)
        elif len(x) == 2:
            return z3.BitVecVal(int(x[1], 8), bitlen)
        else:
            return z3.BitVecVal(int(x[0]), bitlen)

    id_t_2_z3 = {
        ptx.integer_literal: lambda x: z3.BitVec(x, bitlen),
        ptx.float_literal: z3.Real,
        ptx.double_literal: z3.Real,
        ptx.predicate_const: z3.Bool
    }
    return {
        ptx.integer_literal: intern_int,
        ptx.float_literal: lambda x: z3.RealVal(struct.unpack('f', x)[0]),
        ptx.double_literal: lambda x: z3.RealVal(struct.unpack('d', x)[0]),
        ptx.predicate_const: lambda x: z3.BoolVal(bool(x)),
        ptx.identifier: lambda x: id_t_2_z3[ident_t](''.join(x))
    }[typ](arg)
Пример #10
0
def check_e12():

    r120 = z3.IntVal(120)
    r444 = z3.IntVal(444)
    r1_2 = z3.RealVal(1.2)
    r2_1 = z3.RealVal(2.1)

    # segfaults
    e12 = z3.SetSort(z3.IntSort())
    z3.SetAdd(e12, 12)

    constraints = [
        #z3.IsMember(r1_2, e12),
        #z3.IsMember(r2_1, e12),
    ]

    s = z3.Solver()
    for c in constraints:
        s.add(c)

    print('checking', s, s.check())
    satisfied = str(s.check()) == 'sat'
    assert satisfied, s
Пример #11
0
    def getZ3Object(self, increment=False):
        """
        Returns the z3 object for this variable
        """

        if increment:
            self.increment()

        if self.value is None:
            return z3.Real("{0}{1}@{2}".format(self.count, self.varName,
                                               self.ctx),
                           ctx=self.state.solver.ctx)

        return z3.RealVal(self.value)
Пример #12
0
    def __new_constant__(self, constant, code: int):
        """
		:param constant: bool | int | float
		:param code:
		:return:
		"""
        if isinstance(constant, bool):
            return z3.BoolVal(constant)
        elif isinstance(constant, int):
            if code == self.__s_code__:
                return z3.BitVecVal(constant, self.longLength)
            else:
                return z3.IntVal(constant)
        else:
            return z3.RealVal(constant)
Пример #13
0
def model2var_realVec(model, outputVarList, var2dim_dict):
    sample_dict = {}
    for output_arr in outputVarList:
        num_elements = var2dim_dict[str(output_arr)]
        x_arr = [model[output_arr[i]] for i in range(num_elements)]
        # TODO: replace all vars which have no models with 0
        # Is this handling correct?
        x_arr = [z3.RealVal(0) if x is None else x for x in x_arr]
        x_arr = [z3val2pyval(x) for x in x_arr]
        #print(str(output_arr))
        #print(x_arr)
        sample_dict[str(output_arr)] = x_arr
    #print(sample_dict)
    #exit()
    return sample_dict
Пример #14
0
def pool2d_avg_0(kx, ky, sx, sy, pad, A):
    assert pad in [PD_MODE_SAME, PD_MODE_VALID]
    sa = A.shape
    require(len(sa) == 4)
    require(sx > 0 and sy > 0)
    if pad == PD_MODE_SAME:  # same padding
        ox = (sa[2] + sx - 1) / sx
        oy = (sa[3] + sy - 1) / sy
        if sa[2] % sx == 0:
            totalPadH = max(kx - sx, 0)
        else:
            totalPadH = max(kx - (sa[2] % sx), 0)
        if sa[3] % sy == 0:
            totalPadW = max(ky - sy, 0)
        else:
            totalPadW = max(ky - (sa[3] % sy), 0)
        px = (totalPadH + 1) / 2
        py = (totalPadW + 1) / 2
    elif pad == PD_MODE_VALID:  # valid padding
        ox = (sa[2] - kx) / sx + 1
        oy = (sa[3] - ky) / sy + 1
        px = 0
        py = 0
    else:
        assert False

    so = (sa[0], sa[1], ox, oy)
    require(ox > 0 and oy > 0)
    C = Tensor.zeros(so)
    for n in range(so[0]):
        for c in range(so[1]):
            for h in range(so[2]):
                for w in range(so[3]):
                    value = 0
                    for kh in range(kx):
                        for kw in range(ky):
                            posH = h * sx + kh - px
                            posW = w * sy + kw - py
                            assert -px <= posH <= sa[2] + px, posH
                            assert -py <= posW <= sa[3] + py, (posW, h, w, sx,
                                                               sy, kh, kw, py,
                                                               so)
                            if posH >= 0 and posH < sa[
                                    2] and posW >= 0 and posW < sa[3]:
                                value += A[n, c, posH, posW]
                    C[n, c, h, w] = value / z3.RealVal(kx * ky)
    C.splits = (A.splits[0], A.splits[1], (), ())
    return C
Пример #15
0
#    ne.name: (lambda args, context: args[0] != args[1]),
#    Sum.name: (lambda args, context: z3.Sum(args)),
#    Product.name: (lambda args, context: z3.Product(args)),
#    gt.name: (lambda args, context: args[0] > args[1]),
#    ge.name: (lambda args, context: args[0] >= args[1])
}

_built_in_z3_sorts = {
    Int.name: z3.IntSort,
    Real.name: z3.RealSort,
    Bool.name: z3.BoolSort
}

_built_in_z3_sort_values = {
    Int.name: (lambda s, ctxt: z3.IntVal(int(s), ctxt)),
    Real.name: (lambda s, ctxt: z3.RealVal(float(s), ctxt)),
    Bool.name: (lambda s, ctxt: z3.BoolVal(bool(s), ctxt))
}


###############################################################################
#
# Convert Boole expressions to Z3 expressions
#
###############################################################################


def z3_to_fun(z3_expr):
    """Takes a FuncInterp instance, and returns the function which
    takes as input a z3 expression and returns the value of the
    corresponding expression.
Пример #16
0
def getDecimalValue(v0):
    v = z3.RealVal(str(v0))
    return long(v.numerator_as_long()) / v.denominator_as_long()
Пример #17
0
 def _from_mc_result_to_z3_ref(self, val):
     #TODO super nasty.
     return z3.RealVal(str(val))
Пример #18
0
import z3

if __name__ == '__main__':
    x = z3.Real('x')
    const = z3.RealVal(1) / 3
    z3.set_option(rational_to_decimal=True)
    z3.solve(x + const == 0)
Пример #19
0
def z3_matchLeftAndRight(left,right,op):
    """Appropriately change the two variables so that they can be used in an
    expression
    
    Parameters
    ----------
    left,right : pyObjectManager.Int.Int or pyObjectManager.Real.Real or pyObjectManager.BitVec.BitVec or pyObjectManager.Char.Char
        Objects to be matched
    op : ast.*
        Operation that will be performed


    Returns
    -------
    tuple
        (z3ObjectLeft,z3ObjectRight) tuple of z3 objects that can be used in an expression
    
    
    The purpose of this function is to match two pyObjectManager.* variables to
    a given ast operation element. Z3 needs to have matched types, and this
    call will not only match the objects, but also attempt to concretize input
    wherever possible.

    Example
    -------
    If you want to auto-match BitVector sizes::

        In [1]: import z3, pyState.z3Helpers, ast
    
        In [2]: from pySym.pyObjectManager.BitVec import BitVec

        In [3]: from pySym.pyState import State

        In [4]: state = State()
    
        In [5]: x = BitVec("x",0,16,state=state)

        In [6]: y = BitVec("y",0,32,state=state)
    
        In [7]: l,r = pyState.z3Helpers.z3_matchLeftAndRight(x,y,ast.Add())

        In [8]: s = z3.Solver()

        In [9]: s.add(l + r == 12)

        In [10]: s
        Out[10]: [SignExt(16, 0x@0) + 0y@0 == 12]

        In [11]: s.check()
        Out[11]: sat

    """

    lType = type(left)
    rType = type(right)

    # If it's char, just grab the BitVec object
    if lType is Char:
        left = left.variable
        lType = type(left)
    if rType is Char:
        right = right.variable
        rType = type(right)

    logger.debug("z3_matchLeftAndRight: Called to match {0} and {1}".format(type(left),type(right)))
    needBitVec = True if type(op) in [ast.BitXor, ast.BitAnd, ast.BitOr, ast.LShift, ast.RShift] else False
    # TODO: If the two sizes are different, we'll have problems down the road.
    bitVecSize = max([c.size for c in [b for b in [left,right] if type(b) is BitVec]],default=Z3_DEFAULT_BITVEC_SIZE)

    #####################################
    # Case: Both are already BitVectors #
    #####################################
    # Check length. Extend if needed.
    if type(left) is BitVec and type(right) is BitVec:
        logger.debug("z3_matchLeftAndRight: Matching BitVecLength @ {0} (left={1},right={2})".format(bitVecSize,left.size,right.size))
        if left.size < right.size:
            # Sign extend left's value to match
            left = z3.SignExt(right.size-left.size,left.getZ3Object())
            right = right.getZ3Object()
        elif right.size > left.size:
            right = z3.SignExt(left.size-right.size,right.getZ3Object())
            left = left.getZ3Object()
        
        # Sync-up the output variables
        left = left.getZ3Object() if type(left) in [Int, Real, BitVec] else left
        right = right.getZ3Object() if type(right) in [Int, Real, BitVec] else right

        logger.debug("z3_matchLeftAndRight: Returning {0} and {1}".format(type(left),type(right)))

        return left,right

    #####################################
    # Case: One is BitVec and one isn't #
    #####################################
    # For now only handling casting of int to BV. Not other way around.
    if (lType is BitVec and rType is Int) or (rType is Int and needBitVec):
        # If we need to convert to BitVec and it is a constant, not variable, do so more directly
        if right.isStatic():
            right = z3.BitVecVal(right.getValue(),bitVecSize)
        # Otherwise cast it. Not optimal, but oh well.
        else:
            right = z3_int_to_bv(right.getZ3Object(),size=bitVecSize)

    if (rType is BitVec and lType is Int) or (lType is Int and needBitVec):
        if left.isStatic():
            left = z3.BitVecVal(left.getValue(),bitVecSize)
        else:
            left = z3_int_to_bv(left.getZ3Object(),size=bitVecSize)
        
    ################################
    # Case: One is Int one is Real #
    ################################
    # So long as this isn't modular arithmetic, let's change to Real things
    if lType is Real and rType is Int and type(op) is not ast.Mod:
        if right.isStatic():
            right = z3.RealVal(right.getValue())
        else:
            # TODO: Z3 is really bad at handling these...
            right = z3.ToReal(right.getZ3Object())

    if rType is Real and lType is Int and type(op) is not ast.Mod:
        if left.isStatic():
            left = z3.RealVal(left.getValue())
        else:
            # TODO: Z3 is really bad at handling these...
            left = z3.ToReal(left.getZ3Object())


    ############################################
    # Case: One is Int one is Real for ast.Mod #
    ############################################
    # So long as this isn't modular arithmetic, let's change to Real things
    if lType is Real and rType is Int and type(op) is ast.Mod:
        if left.isStatic():
            leftVal = left.getValue()
            left = z3.IntVal(leftVal)
            if int(leftVal) != leftVal:
                logger.warn("Truncating value for Modular Arithmetic. That may or may not be what was intended!")

        # See if we can swing this the other direction
        elif right.isStatic():
            rightVal = right.getValue()
            right = z3.RealVal(rightVal)
            

    if rType is Real and lType is Int and type(op) is ast.Mod:
        if right.isStatic():
            rightVal = right.getValue()
            right = z3.IntVal(rightVal)
            if int(rightVal) != rightVal:
                logger.warn("Truncating value for Modular Arithmetic. That may or may not be what was intended!")

        # See if we can swing this the other direction
        else:
            left = z3.RealVal(left.getValue())
    
    # Sync-up the output variables
    left = left.getZ3Object() if type(left) in [Int, Real, BitVec] else left
    right = right.getZ3Object() if type(right) in [Int, Real, BitVec] else right

    logger.debug("z3_matchLeftAndRight: Returning {0} and {1}".format(type(left),type(right)))

    return left,right
Пример #20
0
def noise_sensor(ram_kb=32,
                 storage_kb=128,
                 transmit_period_hours=1,
                 noise_window=1 / 8,
                 noiseid_window=60,
                 noiseid_samplerate=4,
                 noiseid_max_percent=0.01,
                 mic_a=500e-6,
                 sleep_a=250e-6,
                 cpu_run_a=2e-3,
                 modem_a=50e-3,
                 battery_selfdischarge=0.05,
                 battery_days=365,
                 battery_mah=1400):

    import z3

    # take into account self-discharge
    battery_mah = battery_mah * (1.0 - battery_selfdischarge)

    battery_uas = battery_mah * 1000 * 3600
    energy_day = battery_uas / battery_days

    transmit_period = transmit_period_hours / 24 * 60 * 60

    assert noiseid_samplerate < 10  # keep unintelligeble
    assert noiseid_samplerate > 1  # keep useful

    noiseid_data = octave_bands_ram(noiseid_window, noiseid_samplerate)
    noiseid_max_samples = noiseid_max_percent * (transmit_period_hours * 60 *
                                                 60 / noiseid_window)

    noiseid_storage = noiseid_data * noiseid_max_samples
    noise_storage = transmit_period_hours * 60 * 60 / noise_window

    data_sizes = [
        noise_storage,
        noiseid_storage,
    ]
    storage_needed = sum(data_sizes)
    storage_size = storage_kb * 1000

    transmit_time = radio_time(sum(data_sizes))
    # noise sent as one packet, noiseid as N packets
    transmit_ram = max(noise_storage, noiseid_data)

    print('t time', transmit_time)

    ram_use = [
        z3.IntVal(256 * 8),  # audio buffers
        z3.IntVal(noiseid_data),
        z3.IntVal(transmit_ram),
    ]
    cpu_ram = z3.Int('cpu_ram')

    cpu_use = [
        (16e-6, 16e-3),  # audio read
        (160e-6, 16e-3),  # noise calc
        (transmit_time, transmit_period),  # transmit
    ]
    cpu_use_sum = sum(t / p for t, p in cpu_use)

    assert cpu_use_sum < 1.0, cpu_use
    assert cpu_use_sum > 0.0, cpu_use

    def energy(amp, seconds=1.0, period=1.0):
        ua = amp * 1e6
        dutycycle = seconds / period
        tot = ua * dutycycle
        print('e', tot, dutycycle)
        return tot

    energy_use = [
        z3.RealVal(energy(mic_a)),  # base, microphone
        z3.RealVal(energy(sleep_a)),  # base, sleeping
        z3.RealVal(energy(modem_a, transmit_time,
                          transmit_period)),  # transmit
    ]
    energy_use += [z3.RealVal(energy(cpu_run_a, *c)) for c in cpu_use]
    energy_budget = z3.Int('energy_budget')
    energy_spend = z3.Real('energy_use')

    ram_left = z3.Int('ram_left')
    energy_left = z3.Real('energy_left')
    storage_left = z3.Int('storage_left')

    print('b', (energy_day / (1000 * 24)) * battery_days)

    constraints = [
        cpu_ram == ram_kb * 1000,
        energy_budget == energy_day,
        ram_left == cpu_ram - z3.Sum(ram_use),
        energy_spend == z3.Sum(energy_use),
        energy_left == energy_budget - energy_spend,
        storage_left == z3.IntVal(storage_size) - z3.IntVal(storage_needed),
        ram_left > 0,
        energy_left > 0,
        storage_left > 0,
    ]

    s = z3.Solver()
    for c in constraints:
        s.add(c)
    return s
Пример #21
0
    def _parseSmt1String(self, string):
        #self._logger.setVerbose(True)
        stack = list()
        functionSymbols = '&|~<=*+-'
        try:
            string = string.replace('\n', '').split('(')
            idx = 0
            for pos, elem in enumerate(string):
                self._logger.writeToLog('{} - reading :{}:'.format(pos, elem))
                if elem == '':
                    continue

                elemL = elem.split()
                # ALL lines should start with '('
                if elemL[0] in functionSymbols:
                    stack.append(elemL[0])
                elif elemL[0] == 'var':
                    varName = elemL[2].replace(')', '')
                    if elemL[1] == 'bool':
                        formula = z3.Bool(varName)
                        stack.append(self._abstraction(formula))
                    elif elemL[1] == 'real':
                        formula = z3.Real(varName)
                        stack.append(formula)
                    elif elemL[1] == 'int':
                        formula = z3.Int(varName)
                        stack.append(formula)
                    else:
                        raise Exception(
                            'Unknown Variable format: {}'.format(elemL))
                elif elemL[0] == 'const':
                    const = elemL[2].replace(')', '')
                    if elemL[1] == 'real':
                        stack.append(z3.RealVal(const))
                    elif elemL[1] == 'int':
                        stack.append(z3.IntVal(const))
                    else:
                        raise Exception(
                            'Unknown Constant format: {}'.format(elemL))
                else:
                    raise Exception('Unknown format : {}'.format(elemL))

                closedBrackets = elem.count(')') - 1
                self._logger.writeToLog(
                    "{} - new element in stack: {}\t,cB {}".format(
                        pos, stack[-1], closedBrackets))

                if closedBrackets < 1:
                    continue

                while closedBrackets > 0:
                    self._logger.writeToLog('{} - stack: {},{}'.format(
                        pos, stack, closedBrackets))
                    tmpPredi = []
                    pred = None
                    while True:
                        pred = stack.pop()
                        #if isinstance(pred,Predicate) or isinstance(pred,z3.BoolRef) or str(pred).replace('.','',1).isdigit():
                        #if z3.is_rational_value(pred) or z3.is_int_value(pred) or z3.is_int(pred) or z3.is_real(pred) or z3.is_bool(pred):
                        if isinstance(pred, float) or isinstance(
                                pred, int) or z3.is_int(pred) or z3.is_real(
                                    pred) or z3.is_bool(pred):
                            tmpPredi.append(pred)
                        else:
                            if len(tmpPredi) == 1:
                                tmpPredi = tmpPredi[0]
                            else:
                                tmpPredi = tmpPredi[::-1]
                            break
                    self._logger.writeToLog('{} - {} is applied to {}'.format(
                        pos, pred, tmpPredi))
                    newElem = self._mapFunctionSymbol(pred)(tmpPredi)
                    # newElemSimplified = z3.simplify(newElem)
                    stack.append(newElem)
                    self._logger.writeToLog(
                        "{} - new element in stack: {}\t,cB {}".format(
                            pos, stack[-1], closedBrackets))
                    closedBrackets -= 1
                self._logger.writeToLog('{} - finished :{}:'.format(
                    pos, stack))
        except Exception as e:
            self._logger.writeToLog(
                "Some Error : {}\n\t Occured parsing formula: {}".format(
                    e, string))
            raise e

        if len(stack) != 1:
            raise Exception("Parsing Error, stack != 1")
        return self._recusiveSimplification(stack[0])
Пример #22
0
def cfp_to_z3(e,solver=None):
    return z3.RealVal(e.v)
Пример #23
0
def cfp_to_z3(e, slv=None):
    return z3.RealVal(e.v)
Пример #24
0
Файл: smt.py Проект: LRGH/amoco
def cfp_to_z3(e, slv=None):
    "translate cfp expression into its z3 RealVal form"
    return z3.RealVal(e.v)
Пример #25
0
def opamp_components():

    # Components of our system
    components = dict(
        r_in=z3.Int('r_in'),
        r_f=z3.Int('r_f'),
        c_in=z3.Int('c_in'),
        c_out=z3.Int('c_out'),
        c_f=z3.Int('c_f'),
    )

    # XXX: capacitors in picofarad, to keep them integer valued

    # The foreign systems we are connecting to
    # for example a piezo element on input,
    # and a line-level amplifier on output
    input_z = 1e6
    output_z = 10e3

    # Actual selected
    f_upper = z3.Real('f_upper')
    f_lower = z3.Real('f_lower')
    gain = z3.Real('gain')

    # Functional requirements for our amplifier
    gain_desired = z3.RealVal(22.0)
    gain_tolerance = z3.RealVal(0.05)  # relative
    functional_requirements = [
        (gain * (1 + gain_tolerance) >= gain_desired),
        (gain * (1 - gain_tolerance) <= gain_desired),
        #f_upper > z3.RealVal(10e3),
        #f_upper < z3.RealVal(20e3),
        f_lower < z3.RealVal(10.0),
        f_lower > z3.RealVal(1.0),
    ]

    # How the amplifier circuit works
    # XXX: assumes that the filters are independent (no interactions)
    # reasonable in many practical cases, but not guaranteed
    f_in = z3.Real('f_in')
    f_out = z3.Real('f_out')
    c = components
    circuit_constraints = [
        c['r_f'] == 3300,
        #c['c_f'] > 1,
        c['c_f'] != 0,
        gain == opamp_gain_ni(c['r_in'], c['r_f']),
        #f_in == filter_cutoff(input_z, c['c_in']*z3.RealVal(1e-6)),
        #f_out == filter_cutoff(output_z, c['c_out']*z3.RealVal(1e-6)),
        f_lower < f_in,
        f_lower < f_out,
        f_upper == filter_cutoff(c['r_f'], c['c_f'], z3.RealVal(1e-6)),
    ]
    # TODO: constraint

    # all components must be in E12
    component_values = e_values()
    component_constraints = []
    #component_constraints = [ v > 0 for v in components.values() ]
    #component_constraints += [ v < 1000000000 for v in components.values() ]
    #component_constraints = [ component_value_constraint(v, component_values) for v in components.values() ]

    # TODO: match components against others on the board
    # EX: decoupling capacitors

    constraints = functional_requirements + \
        circuit_constraints + \
        component_constraints

    zmodels = get_models(constraints, M=100)

    models = []
    for model in zmodels:
        results = {}
        for var in model:
            results[str(var)] = model[var]

        models.append(results)

    resistors = set([v for v in models[0].keys() if v.startswith('r_')])
    capacitors = set([v for v in models[0].keys() if v.startswith('c_')])
    print(resistors, capacitors)

    def unique_component_values(res):
        r_values = set(v for k, v in res.items() if k in resistors)
        c_values = set(v for k, v in res.items() if k in capacitors)
        #print(r_values, c_values)
        print()
        return len(r_values) + len(c_values)

    preferred = sorted(models, key=lambda r: unique_component_values(r))

    print(preferred[0])
Пример #26
0
import re

from typing import Tuple, Dict, Union, Set, List

FP_OPS = ["fmul", "fdiv", "fadd", "fsub"]
IGNORED_OPS = ["ret", "br"]

VAR_REGEX = re.compile(r"%[a-zA-Z0-9]+")
NUM_REGEX = re.compile(r"[0-9]+.[0-9]+e(\+|\-)[0-9]+")
HEX_REGEX = re.compile(r"0x[0-9a-fA-F]+")
ARG_REGEX = re.compile(
    r"(%s)|(%s)|(%s)" %
    (VAR_REGEX.pattern, NUM_REGEX.pattern, HEX_REGEX.pattern))

DBL_MAX = z3.RealVal(
    "179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0"
)  # noqa
DBL_MIN = z3.RealVal(
    "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000222507385850720138309023271733240406421921598046233183055332741688720443481391819585428315901251102056406733973103581100515243416155346010885601238537771882113077799353200233047961014744258363607192156504694250373420837525080665061665815894872049117996859163964850063590877011830487479978088775374994945158045160505091539985658247081864511353793580499211598108576"
)  # noqa

FloatArith = Union[float, z3.ArithRef]


class Constraint:
    def __init__(self, name: str, instr: str, formula: z3.ArithRef):
        self.name = name
        self.instruction = instr
        self.formula = formula

    def _and(self, other: z3.ArithRef):
Пример #27
0
 def walk_real_constant(self, formula, **kwargs):
     frac = formula.constant_value()
     n,d = frac.numerator, frac.denominator
     rep = str(n) + "/" + str(d)
     return z3.RealVal(rep)