Пример #1
0
	def __init__(self,param):
		self.param = param
		self.Gate = Gate('',self)
		self.NeuronGate0 = NeuronGate(self.Gate, Input='input', W='w0',
									   bias='b0', o='o0', activeFunc=SigmoidActivator())
		self.NeuronGate1 = NeuronGate(self.Gate, Input='o0', W='w1',
									  bias='b1', o='o1', activeFunc=None)
Пример #2
0
	def __init__(self,lstmParam,state_size,output_size,index,jsonModel=None):
		self.index = index
		self.param = lstmParam
		self.jsonModel = jsonModel
		self.Gate = Gate('', self)
		self.Gates = jsonModel.getGatesAndParam(self)


		#self.prev_s = np.zeros((state_size, 1))
		#self.prev_h = np.zeros((output_size,1))
		#self.dprev_s = np.zeros_like(self.prev_s)
		#self.dOutput = np.zeros_like(self.prev_h)
		self.cache = 'prev_h=None,prev_s=None'
Пример #3
0
class bp:
	def __init__(self,param):
		self.param = param
		self.Gate = Gate('',self)
		self.NeuronGate0 = NeuronGate(self.Gate, Input='input', W='w0',
									   bias='b0', o='o0', activeFunc=SigmoidActivator())
		self.NeuronGate1 = NeuronGate(self.Gate, Input='o0', W='w1',
									  bias='b1', o='o1', activeFunc=None)

	def forward(self,X):
		self.input = X
		self.NeuronGate0.forward()
		self.NeuronGate1.forward()
		return self.o1

	def backward(self,delta):
		self.do1 =  delta
		self.Gate.runBackward()
Пример #4
0
def TestGateTruth(gateType):
    """
    Creates truth table for given gateType

    Input: String - AND, OR etc.
    """

    # All possible inputs for the gates
    Inputs = [(0,0), (0,1), (1,0), (1,1)]


    print('---%s - Truthtable---' % gateType)

    # Iterate over all posible binary inputs
    for i in Inputs:
        TGate = Gate(i[0],i[1])

        if gateType == 'AND':
            output = TGate.AND()
            print('Input: %d, %d | Output: %d' % (i[0],i[1],output))

        if gateType == 'OR':
            output = TGate.OR()
            print('Input: %d, %d | Output: %d' % (i[0],i[1],output))

        if gateType == 'NOT':
            output = TGate.NOT()
            print('Input: %d, %d | Output: %d' % (i[0],i[1],output))

        if gateType == 'NAND':
            output = TGate.NAND()
            print('Input: %d, %d | Output: %d' % (i[0],i[1],output))

        if gateType == 'NOR':
            output = TGate.NOR()
            print('Input: %d, %d | Output: %d' % (i[0],i[1],output))

        if gateType == 'XOR':
            output = TGate.XOR()
            print('Input: %d, %d | Output: %d' % (i[0],i[1],output))

        if gateType == 'XNOR':
            output = TGate.XNOR()
            print('Input: %d, %d | Output: %d' % (i[0],i[1],output))

    # Spacer for next TestGateTruth call in Tests.py
    print('')
Пример #5
0
 def gate(self):
     """ Return a gate"""
     gate_node = Gate("gate", 1)
     gate_node.scale_total(100)
     gate_node.translate(z=-100)
     self.elevate(gate_node)
     return gate_node
Пример #6
0
def extractGate(path):
    workbook = xlrd.open_workbook(path)
    sheet = workbook.sheet_by_name('Gates')
    gates = []
    gates_matrix = []
    for i in range(sheet.nrows):
        if i != 0:
            data = sheet.row_values(i)
            gate = Gate(data[0], data[1], data[2], data[3], data[4], data[5])
            gates.append(gate)
            gates_matrix.append(data)

    return gates, gates_matrix
Пример #7
0
def OR(children: list):
    OR_gate = Gate('OR')
    for child in children:
        if type(child) is str:
            OR_gate.add_variable(child)
        elif type(child) is Gate:
            OR_gate.add_gate(child)
    return OR_gate
Пример #8
0
def AND(children: list):
    AND_gate = Gate('AND')
    for child in children:
        if type(child) is str:
            AND_gate.add_variable(child)
        elif type(child) is Gate:
            AND_gate.add_gate(child)
    return AND_gate
Пример #9
0
def processLogic(word, word2):
    #print word,word2
    if (len(word) == 4):
        inputNode1 = word[1]
        inputNode2 = word[2]
        outputNode = word[3]
        nodeObj1 = None
        nodeObj2 = None
        nodeObj3 = None
        if inputNode1 not in globalVars.dictOfInputs.keys():
            if inputNode1 not in globalVars.dictOfInternalSignals.keys():
                nodeObj1 = Node(inputNode1, False, False)
                globalVars.dictOfInternalSignals[inputNode1] = nodeObj1
            else:
                nodeObj1 = globalVars.dictOfInternalSignals[inputNode1]
        else:
            nodeObj1 = globalVars.dictOfInputs[inputNode1]

        if inputNode2 not in globalVars.dictOfInputs.keys():
            if inputNode2 not in globalVars.dictOfInternalSignals.keys():
                nodeObj2 = Node(inputNode1, False, False)
                globalVars.dictOfInternalSignals[inputNode2] = nodeObj2
            else:
                nodeObj2 = globalVars.dictOfInternalSignals[inputNode2]
        else:
            nodeObj2 = globalVars.dictOfInputs[inputNode2]

        if outputNode not in globalVars.dictOfOutputs.keys():
            if outputNode not in globalVars.dictOfInternalSignals.keys():
                nodeObj3 = Node(outputNode, False, False)
                globalVars.dictOfInternalSignals[outputNode] = nodeObj3
            else:
                nodeObj3 = globalVars.dictOfInternalSignals[outputNode]
        else:
            nodeObj3 = globalVars.dictOfOutputs[outputNode]

        inpLogicStatus = word2[0]
        outLogicStatus = int(word2[1])
        inputNodeLogicStatus = []
        for elm in inpLogicStatus:
            inputNodeLogicStatus.append(int(elm))

        gateObj = Gate([nodeObj1, nodeObj2], inputNodeLogicStatus, nodeObj3,
                       outLogicStatus)
        nodeObj3.assignParentGate(gateObj)
        globalVars.gateCount += 1
        gateName = "gate_" + str(globalVars.gateCount)
        nodeObj1.addSuccessorGate(inputNodeLogicStatus[0], gateObj, gateName)
        nodeObj2.addSuccessorGate(inputNodeLogicStatus[1], gateObj, gateName)
Пример #10
0
 def create_gates(gates_str):
     gate_list = gates_str.split('],\n')
     parsed_gates = []
     for gate in gate_list:
         # Parsing gate
         gate_list = gate.replace('[', '').replace(']', '').split(',')
         # Parsing gate type
         remove_digits = str.maketrans('', '', digits)
         gate_type = gate_list[0].translate(remove_digits)
         # Create gate object
         Gate_Constructor = Gate.create_gate(gate_type)
         gate = Gate_Constructor(gate_type, gate_list[1], gate_list[2],
                                 gate_list[3:])
         parsed_gates.append(gate)
     return parsed_gates
Пример #11
0
def class_type(tree):
    tmp_gate = Gate(tree['gate'])
    global index_used
    for child in tree['children']:
        if child == 'var':
            index_used += 1
            tmp_gate.add_variable('x[' + str(index_used) + ']')
    # else:
    # 	tmp_gate.add_gate(class_type(child))
    for child in tree['children']:
        if child != 'var':
            tmp_gate.add_gate(class_type(child))
    return tmp_gate
Пример #12
0
import unittest
from Gate import Gate

gate = Gate(2.0)

class GateTests(unittest.TestCase):
	#def testGate(self):
	#	self.assertTrue(gate.gate_welcomes())

	def assertSelf(self):
		self.true()

	def assertPaid(self):
		pay = gate.paid
		self.assertEqual(pay, 2.0)

if __name__ == '__main__':
	unittest.main()
def main():

    gc.enable()
    gc.set_debug(gc.DEBUG_LEAK)
    dump_garbage()

    if len(sys.argv) < 2:
        print "Usage: %s basename" % sys.argv[0]
        sys.exit(1)
    basename = sys.argv[1]

    os.chdir(basename)

    inputs = []
    outputs = []
    gates = []
    for line in file(basename + ".easy"): # easy refers to this new easy-to-parse file format, instead of nasty verilog needing a complex parser
        if line.startswith("#"):
            continue

        # the python code doesn't need the NUM* lines, but they should make it easier for the c implementation
        if line.startswith("NUMINPUTS"):
            num_inputs = int(line.strip().split()[1])
        elif line.startswith("NUMOUTPUTS"):
            num_outputs = int(line.strip().split()[1])
        elif line.startswith("NUMGATES"):
            num_gates = int(line.strip().split()[1])
        elif line.startswith("INPUT"):
            input, net = line.strip().split()
            inputs.append(net)
        elif line.startswith("OUTPUT"):
            output, net = line.strip().split()
            outputs.append(net)
        else:
            items = line.strip().split()
            gtype = items[0]
            outnet = items[1]
            innets = items[2:]
            #print "Parsed gate:", (gtype, outnet, innets)
            gates.append( (gtype, outnet, innets) )

    print "Loaded %d inputs, %d outputs, and %d gates from '%s.easy'" % (len(inputs), len(outputs), len(gates), basename)

    # we store the circuit structure and state in a hashtable that maps output net -> gate
    # note: we treat circuit inputs as specialized gates of type INPUT
    gates_by_outnet = {}

    # let's convert the gates into our structured netlist graph
    # First, we have to create all the Gate objects for the inputs and gates...
    for outnet in inputs:
        gtype = "INPUT"
        g = Gate(gtype, outnet)
        gates_by_outnet[outnet] = g
    for gtype, outnet, innets in gates:
        # gates look like this: ("NAND", "OUTNET", ["IN1", "IN2", ...])
        g = Gate(gtype, outnet)
        g.innets = innets
        gates_by_outnet[outnet] = g

    # Now that we have created all our gates, we have to go back and link them together
    for outnet in gates_by_outnet.keys():
        # for each gate, we need to set up the fanin and fanout lists
        # each gate source only knows its fanin (ie. Y = AND(A, B) means we know our fanin gates are A and B), so we set that, and then update the fanin gates' fanout lists
        g = gates_by_outnet[outnet]
        if g.gtype == "INPUT":
            # move along, nothing to do here (inputs have no fanin, our fanout list will be updated by the gates we fanout to)
            continue
        for innet in g.innets: # g.innets is a list of the nets that are input to this gate
            input_gate = gates_by_outnet[innet]
            g.fanin.append(innet) # add this gate's outnet to our fanin list
            input_gate.fanout.append(g.outnet) # add my outnet to the input's fanout list

    # read in the test vectors: (v1, v2, resp2)
    test_vectors = []
    for line in file(basename + ".tests"):
        if line.startswith("NUMTESTS"):
            continue # we don't need to parse this line
        test_vectors.append(line.strip().split())
    print "Read %d tests from '%s.tests'" % (len(test_vectors), basename)

    # load the fault list from basename.faults
    faults = [] # (outnet, rising=True or False)
    for line in file(basename + ".faults.gpu"):
        if line.startswith("NUM"):
            continue # we don't need to parse this line (only for GPU code)
        net, pol = line.strip().split()
        polarity = True if pol == "1" else False
        #print (net, polarity)
        faults.append( (net, polarity) )

    dump_garbage()
    # we need to simulate each test vector pair in turn
    responses_by_test = [] # this is where we store the matrix of responses, first index is test, second index is fault
    print "Starting fault simulation for each test, for each fault"
    time_start_ms = int(round(time.time() * 1000))
    test_id = 0
    time_start = time.time() # seconds since the epoch
    time_step = time_start
    num_tests = len(test_vectors)
    state = None
    for test in test_vectors:
        # fault simulate the circuit to get the baseline responses to v1 and v2
        v1 = zip(inputs, test[0])
        v2 = zip(inputs, test[1])
        if state:
            del state
        state = copy.deepcopy(gates_by_outnet) # WTF TODO why do we have to start over with a fresh circuit state!?!?
        simulate(state, v1=v1, v2=v2, external_events=[])
        #state_dump(state)

        #print "  Analyzing %d faults..." % len(faults)
        responses = []
        prior_outnet = None
        fault_id = 0
        for outnet, rising in faults:
            #print "Fault %d" % fault_id
            #print "-----------------------------------------------------"
            #print "    Outnet '%s', rising fault? %s, v1: %s, v2: %s" % (outnet, "true" if rising else "false", state[outnet].values[0], state[outnet].values[1])

            # find our faulty gate and mark it as the fault site of the proper polarity
            fs = state[outnet]
            fs.fault_site = True
            fs.fault_rising = rising

            if prior_outnet:
                external_events = [prior_outnet, outnet]
            else:
                external_events = [outnet]
            simulate(state, v1=[], v2=[], external_events=external_events)
            # record output
            output_v1 = "".join([state[x].values[0] for x in outputs])
            output_v2 = "".join([state[x].values[1] for x in outputs])
            resp = ""
            for i in range(len(outputs)):
                val = state[outputs[i]].values[1]
                if val != "H":
                    resp += val
                else: # we replace hazard values with the original value expected
                    resp += test[2][i]
            responses.append(resp)

            # if we aren't doing the expensive deepcopy each time, let's try this
            fs.fault_site = False
            prior_outnet = outnet

            fault_id += 1

        responses_by_test.append(responses)

        time_so_far = time.time() - time_start # seconds
        progress = (test_id + 1) / float(num_tests) # we add one here because we just finished the current test_id
        estimated_time_left = MLButil.estimated_time_left(time_so_far, progress)
        print "test_id: %5d (%3.2f%%\t - %s step, %s total, %s left)" % (test_id, 100 * progress, MLButil.pretty_time(time.time() - time_step), MLButil.pretty_time(time_so_far), MLButil.pretty_time(estimated_time_left))
        time_step = time.time()

        test_id += 1
        dump_garbage()

    time_end_ms = int(round(time.time() * 1000))
    print "----------------------------------------------------"
    print "Execution time of fault simulation code: %f seconds" % ((time_end_ms - time_start_ms) / 1000.0)
    #print "%d Fault sites:" % len(faults), " ".join(["%s/%s" % (x[0], "STR" if x[1] else "STF") for x in faults])
    #for i in range(len(responses_by_test)):
        #print "Test %4d, responses:" % i, responses_by_test[i]

    filename = basename + ".dictionary.full"
    print "Writing full response dictionary to '%s'" % filename
    with open(filename, "w") as fid:
        for fault_id in range(len(faults)):
            fid.write(" ".join([responses_by_test[test_id][fault_id] for test_id in range(len(responses_by_test))]) + " \n")
            #print "Fault %d: " % fault_id + " ".join([responses_by_test[test_id][fault_id] for test_id in range(len(responses_by_test))])

    filename = basename + ".dictionary.pf"
    print "Writing pass/fail dictionary to '%s'" % filename
    with open(filename, "w") as fid:
        for fault_id in range(len(faults)):
            fid.write("%s\n" % "".join([("1" if "X" in responses_by_test[test_id][fault_id].upper() else "0") for test_id in range(len(responses_by_test))]))
Пример #14
0
class LSTM_layer:
	def __init__(self,lstmParam,state_size,output_size,index,jsonModel=None):
		self.index = index
		self.param = lstmParam
		self.jsonModel = jsonModel
		self.Gate = Gate('', self)
		self.Gates = jsonModel.getGatesAndParam(self)


		#self.prev_s = np.zeros((state_size, 1))
		#self.prev_h = np.zeros((output_size,1))
		#self.dprev_s = np.zeros_like(self.prev_s)
		#self.dOutput = np.zeros_like(self.prev_h)
		self.cache = 'prev_h=None,prev_s=None'
	def forward(self,input,prev_h=None,prev_s=None):
		if prev_h is None:prev_h = self.prev_h
		if prev_s is None:prev_s = self.prev_s
		setattr(self, self.jsonModel.input, input)

		for db in self.jsonModel.DB:#fromDB
			key = 'o' + self.jsonModel.key2bz(db['key'])
			value = db['text']
			setattr(self,key,eval(value))

		for g in self.Gates:#forward
			str = 'self.' + g.Key + '.forward()'
			#print(g.Value)
			eval(str)

		for db in self.jsonModel.Output:#toDB
			value = 'self.o' + self.jsonModel.key2bz(db['key'])
			key = db['text']
			setattr(self, key, eval(value))
		return self.Output,self.prev_s

	def backward(self,dOutput=None,dprev_s=None):
		if dOutput is None:doutput = self.dOutput
		if dprev_s is None:dprev_s = self.dprev_s
		for db in self.jsonModel.Output:  # fromDB
			key = 'do' + self.jsonModel.key2bz(db['key'])
			value = 'd' + db['text']
			setattr(self, key, eval(value))
		self.Gate.runBackward()#backward

		for db in self.jsonModel.DB:#toDB
			value = 'self.do' + self.jsonModel.key2bz(db['key'])
			key = 'd' + db['text']
			setattr(self, key, eval(value))

		return self.dOutput,self.dprev_s

	def setOutputDelta(self,delta):
		self.dOutput = delta

	def Dropout(self, x, level):
		if level == 0:
			return x
		if level < 0. or level >= 1:  # level是概率值,必须在0~1之间
			raise ValueError('Dropout level must be in interval [0, 1[.')
		retain_prob = 1. - level

		# 我们通过binomial函数,生成与x一样的维数向量。binomial函数就像抛硬币一样,我们可以把每个神经元当做抛硬币一样
		# 硬币 正面的概率为p,n表示每个神经元试验的次数
		# 因为我们每个神经元只需要抛一次就可以了所以n=1,size参数是我们有多少个硬币。
		random_tensor = np.random.binomial(n=1, p=retain_prob,
										   size=x.shape)  # 即将生成一个0、1分布的向量,0表示这个神经元被屏蔽,不工作了,也就是dropout了
		x *= random_tensor
		# x /= retain_prob
		np.true_divide(x, retain_prob, out=x, casting='unsafe')
		return x
Пример #15
0
from Gate import Gate

if __name__ == '__main__':
    print(Gate(0,0).AND())
    print(Gate(1,0).AND())
    print(Gate(1,1).AND())

    print(Gate(0,0).OR())
    print(Gate(1,0).OR())
    print(Gate(1,1).OR())