示例#1
0
	def __init__(self,index):
		QTabWidget.__init__(self)

		self.index=index
		lines=[]

		if inp_load_file(lines,"pulse"+str(self.index)+".inp")==True:
			self.tab_name=inp_search_token_value(lines, "#sim_menu_name")
		else:
			self.tab_name=""


		self.setTabsClosable(True)
		self.setMovable(True)

		self.tmesh = tab_time_mesh(self.index)
		self.addTab(self.tmesh,_("time mesh"))


		self.circuit=circuit(self.index)

		self.addTab(self.circuit,_("Circuit"))

		tab=tab_class()
		tab.init("pulse"+str(self.index)+".inp","Configure")
		self.addTab(tab,"Configure")
    def init(self, index):
        QTabWidget.__init__(self)

        self.index = index

        lines = []
        self.file_name = os.path.join(get_sim_path(),
                                      "is" + str(self.index) + ".inp")
        lines = inp_load_file(self.file_name)
        if lines != False:
            self.tab_name = inp_search_token_value(lines, "#sim_menu_name")
        else:
            self.tab_name = ""

        self.tmesh = tab_fxmesh(self.index)
        self.addTab(self.tmesh, _("Frequency mesh"))
        #if inp().isfile("diagram.inp")==False:
        self.circuit = circuit(self.index,
                               base_file_name="is_fxdomain_data",
                               token="#fxdomain_sim_mode")
        self.addTab(self.circuit, _("Circuit"))

        widget = tab_class(self.file_name)
        self.addTab(widget, _("Simulation"))

        self.fx_domain_file_name = os.path.join(
            get_sim_path(), "is_fxdomain_data" + str(self.index) + ".inp")
        widget = tab_class(self.fx_domain_file_name)
        self.addTab(widget, _("FX domain simulation"))
示例#3
0
    def __init__(self, index):
        QTabWidget.__init__(self)
        css_apply(self, "tab_default.css")
        self.index = index
        lines = []
        self.file_name = os.path.join(get_sim_path(),
                                      "pulse" + str(self.index) + ".inp")
        lines = inp_load_file(self.file_name)
        if lines != False:
            self.tab_name = inp_search_token_value(lines, "#sim_menu_name")
        else:
            self.tab_name = ""

        self.setMovable(True)

        self.tmesh = tab_time_mesh(self.index)
        self.addTab(self.tmesh, _("time mesh"))

        self.circuit = circuit(self.index)

        self.addTab(self.circuit, _("Circuit"))

        tab = tab_class()
        tab.init(self.file_name, _("Configure"))
        self.addTab(tab, _("Configure"))
示例#4
0
 def _hadamard_gate(self):
     """Returns a hadamard gate applied to each qbit of the register
     (excluding the highest bit used to implement `_not_gate`)
     """
     had = circuit()
     for i in range(self._n_qbits):
         had | hadamard(i)
     return had
示例#5
0
def create_specification(chrom, out_fname, data_fname):
    circ = circuit(chrom)
    circ.get_usefull_data()
    circ.check_errors(data_fname)
    circ.get_more_errors()

    ptr = 0
    f = open(out_fname, 'w')
    metadata = "# 8+8 Kogge Stone adder\n"
    metadata += "# Inputs:      " + str(
        circ.inputs).rjust(6) + " Outputs:      " + str(
            circ.outputs).rjust(6) + "\n"
    metadata += "# Gates:       " + str(
        circ.logic_gates).rjust(6) + " Latency:      " + str(
            circ.latency_nodes).rjust(6) + "\n"
    metadata += "# NAND gates:  " + str(
        circ.nand_gates).rjust(6) + " NAND latency: " + str(
            circ.latency_nand_logic).rjust(6) + "\n"
    metadata += "# Transistors: " + str(
        circ.transistors).rjust(6) + " VLSI width:   " + str(
            circ.relative_area).rjust(6) + "LogicalEffort:" + str(
                circ.logical_effort).rjust(6) + "\n"
    metadata += "# \n"
    metadata += "# SHD:  " + str(circ.error_shd).rjust(12) + "\n"
    metadata += "# WSHD: " + str(circ.error_wshd).rjust(12) + "\n"
    metadata += "# SAD:  " + str(circ.error_sad).rjust(12) + "\n"
    metadata += "# \n"
    try:
        metadata += "# Wrong combos:" + str(
            circ.incorrect_combinations).rjust(6) + " Correct comb: " + str(
                circ.correct_combinations).rjust(6) + "\n"
        metadata += "# Avg err: " + ("%.3f" % circ.error_avg2).rjust(
            10) + " Std dev: %.4f" % circ.error_dev2 + "\n"
        metadata += "# Avg err: " + ("%.3f" % circ.error_avg).rjust(
            10
        ) + " Std dev: %.4f" % circ.error_dev + "\tContain correct combinatinos.\n"
        metadata += "# Min: " + str(circ.error_min) + " Q1: " + str(circ.error_qu1) + \
                      " Q2: " + str(circ.error_med) + " Q3: " + str(circ.error_qu3) + " Max: " + str(circ.error_max)+"\n"
        metadata += "# Most freq. error:" + str(circ.error_modus) + "\n"
        metadata += "# \n"
    except:
        pass
    try:
        circ.error_differences
    except:
        circ.error_differences = [0] * (2**circ.inputs)
    metadata += "# Circuit: " + str(circ.circuit)
    metadata += "#\n"
    metadata += "# a    b    vysled [chyba]\n"
    f.write(metadata)
    for i in xrange(2**8):
        for j in xrange(2**8):
            f.write(
                str(i).rjust(3) + " + " + str(j).rjust(3) + " = " +
                str(i + j - circ.error_differences[ptr]).rjust(5) + " [" +
                str(circ.error_differences[ptr]) + "]\n")
            ptr += 1
    f.close()
示例#6
0
    def _hadamard_low_word(self):
        """
        Returns a hadamard gate that acts on all of the qbits in the low word.

        :returns: The hadamard circuit
        :rtype: :class:`circuit.circuit`
        """
        had = circuit()
        for i in range(self._word_qbits):
            had | hadamard(i)
        return had
	def init(self,index):
		self.tab_label=None


		self.index=index
		lines=[]

		if inp_load_file(lines,"fxdomain"+str(self.index)+".inp")==True:
			self.tab_name=inp_search_token_value(lines, "#sim_menu_name")
		else:
			self.tab_name=""


		self.title_hbox=gtk.HBox()

		self.title_hbox.set_size_request(-1, 25)
		self.label=gtk.Label(self.tab_name.split("@")[0])
		self.label.set_justify(gtk.JUSTIFY_LEFT)
		self.title_hbox.pack_start(self.label, False, True, 0)

		self.close_button = gtk.Button()
		close_image = gtk.Image()
   		close_image.set_from_file(os.path.join(get_image_file_path(),"close.png"))
		close_image.show()
		self.close_button.add(close_image)
		self.close_button.props.relief = gtk.RELIEF_NONE

		self.close_button.set_size_request(25, 25)
		self.close_button.show()

		self.title_hbox.pack_end(self.close_button, False, False, 0)
		self.title_hbox.show_all()

		self.notebook=gtk.Notebook()
		self.notebook.show()
		self.fxmesh = tab_fxmesh()
		self.fxmesh.init(self.index)

		self.notebook.append_page(self.fxmesh, gtk.Label(_("Frequency mesh")))

		self.pack_start(self.notebook, False, False, 0)

		self.circuit=circuit()
		self.circuit.init(self.index)

		self.notebook.append_page(self.circuit, gtk.Label(_("Circuit")))

		self.show()
示例#8
0
    def _QFT(self, inv=False):
        """
        Constructs the circuit for a quantum fourier transform (QFT).

        :param bool inv: If `True`, returns an inverse QFT
        :returns: QFT circuit
        :rtype: circuit.circuit
        """
        qft = circuit()
        for i in range(self._word_qbits):
            qft | hadamard(i)
            for j in range(self._word_qbits - i):
                if inv == False:
                    qft | c_phase((i + j + 1), i, (1 / (1 << (1 + j))))
                elif inv == True:
                    qft | c_phase((i + j + 1), i, (-1 / (1 << (1 + j))))
        return qft
	def init(self,index):
		QTabWidget.__init__(self)

		self.index=index
		lines=[]

		if inp_load_file(lines,"fxdomain"+str(self.index)+".inp")==True:
			self.tab_name=inp_search_token_value(lines, "#sim_menu_name")
		else:
			self.tab_name=""


		self.setTabsClosable(True)
		self.setMovable(True)

		self.tmesh = tab_fxmesh(self.index)
		self.addTab(self.tmesh,_("Frequency mesh"))


		self.circuit=circuit(self.index)

		self.addTab(self.circuit,_("Circuit"))
示例#10
0
 def load(self):
     # get dictionary from redis
     d = self.r.hgetall("pool")
     # and sort it all out
     self.circuitlist = []  # empty
     for k in d.keys():
         if k == "hash":
             self.hash = d[k]
         elif k == "pooltime":
             self.pooltime = d[k]
         elif k == "walltime":
             self.walltime = d[k]
         elif k == "airtemp":
             self.airtemp = d[k]
         elif k == "solartemp":
             self.solartemp = d[k]
         elif k == "watertemp":
             self.watertemp = d[k]
         elif k == "spasettemp":
             self.spasettemp = d[k]
         elif k == "poolsettemp":
             self.poolsettemp = d[k]
         elif k == "0" or k == "1" or k == "2" or k == "3" or \
          k == "4" or k == "5" or k == "6" or k == "7" or \
          k == "8" or k == "9" or k == "10" or k == "11" or \
          k == "12" or k == "13" or k == "14" or k == "15" or \
          k == "16" or k == "17" or k == "18": # circuit
             # decode json sting
             cdict = json.loads(d[k])
             self.circuitlist.append(
                 circuit.circuit(k, cdict["name"], cdict["byte"],
                                 cdict["bit"], cdict["value"]))
         elif k == "password":
             self.password = d[k]
         else:
             #print "bad key %s found in load" % k
             a = 1
     self.oldhash = self.hash
	def load( self ):
		# get dictionary from redis
		d = self.r.hgetall( "pool" )
		# and sort it all out
		self.circuitlist = []		# empty
		for k in d.keys():
			if k == "hash":
				self.hash = d[k]
			elif k == "pooltime":
				self.pooltime = d[k]
			elif k == "walltime":
				self.walltime = d[k]
			elif k == "airtemp":
				self.airtemp = d[k]
			elif k == "watertemp":
				self.watertemp = d[k]
			elif k == "spasettemp":
				self.spasettemp = d[k]
			elif k == "poolsettemp":
				self.poolsettemp = d[k]
			elif k == "0" or k == "1" or k == "2" or k == "3" or \
				k == "4" or k == "5" or k == "6" or k == "7" or \
				k == "8" or k == "9" or k == "10" or k == "11" or \
				k == "12" or k == "13" or k == "14" or k == "15" or \
				k == "16" or k == "17" or k == "18":	# circuit
				# decode json sting
				cdict = json.loads(d[k])				
				self.circuitlist.append( circuit.circuit(k,
								cdict["name"],
								cdict["byte"],
								cdict["bit"],
								cdict["value"] ))
			elif k =="password":
				self.password = d[k]
			else:
				#print "bad key %s found in load" % k
				a = 1				
		self.oldhash = self.hash
示例#12
0
    def intiate_Process(self, F, win, servers):
        #this function will send the (public_Key, R1, R2, Function) to the servers
        self.F = F
        self.R = [[0] * 3] * servers
        cid = id(self.F)
        m = [0] * servers

        circ = circuit(self.F, cid)

        for i in range(servers):
            self.R[i][0] = (random.getrandbits(self.SeedSize))
            self.R[i][1] = random.getrandbits(self.SeedSize)
            self.R[i][2] = random.getrandbits(self.SeedSize)

        inwires = circ.YaoGarbledCkt_in(self.R[servers - 1][0])
        winx, winy = inwires[0 + win[0]], inwires[2 + win[1]]
        self.outwires = circ.YaoGarbledCkt_out(self.R[servers - 1][1])

        for i in range(servers - 1):
            m[i] = message(circ, self.R[i])
        m[servers - 1] = message(circ, self.R[servers - 2], winx, winy)

        return m
示例#13
0
    def init(self, index):
        QTabWidget.__init__(self)

        self.index = index
        lines = []
        self.file_name = os.path.join(get_sim_path(),
                                      "fxdomain" + str(self.index) + ".inp")
        lines = inp_load_file(self.file_name)
        if lines != False:
            self.tab_name = inp_search_token_value(lines, "#sim_menu_name")
        else:
            self.tab_name = ""

        self.tmesh = tab_fxmesh(self.index)
        self.addTab(self.tmesh, _("Frequency mesh"))

        self.circuit = circuit(self.index)

        self.addTab(self.circuit, _("Circuit"))

        widget = tab_class()
        widget.init(self.file_name, _("Configure"))
        self.addTab(widget, _("Configure"))
示例#14
0
    8: {
        'name': '#pool light',
        'byte': 1,
        'bit': 7
    },
    9: {
        'name': '#spa light',
        'byte': 2,
        'bit': 0
    },
}

circuitlist = []
for k in circuits.keys():
    circuitlist.append(
        circuit.circuit(k, circuits[k]['name'], circuits[k]['byte'],
                        circuits[k]['bit'], 0))

bExit = False


def sigint_handler(signum, frame):
    global bExit
    # clean up and stop threads
    print "CTRL-C pressed, cleaning up"
    bExit = True


# switch to DEBUG for packet level byte data (but then that writes to the SD
# card so do not keep it there in normal operation

#logging.basicConfig( filename='debug.log', level=logging.DEBUG )
示例#15
0
	if json == 1:
		# take json input and convert to object
		params = jsonmod.loads(query_string)
		updatecontroller = controller.controller([])
		for i in params.keys():
			if i == "spasettemp":
				updatecontroller.setspasettemp( params[i] )
			elif i == "poolsettemp":
				updatecontroller.setpoolsettemp( params[i] )
			elif i == "airtemp":
				updatecontroller.setairtemp( params[i] )
			elif i[:7] == "circuit":	# build circuit
				cir = circuit.circuit( i[7:],
							params[i]['name'],
							params[i]['byte'],
							params[i]['bit'],
							params[i]['value'] )
				updatecontroller.appendcircuit( cir );
			elif i == "token":
				updatecontroller.setpassword( params[i] )
			else:
				# nothing, ignore
				a = 1
	else:
		# take input and convert to object
		if 'query_string' in globals():
			params = dict(cgi.parse_qsl(query_string))
		else:
			params = {}
示例#16
0
import numpy as np
from math import sqrt

#Test application - Entanglement

q0 = state("q0", np.array([1, 0]))
hadamard = operator(
    "H", np.array([[1 / sqrt(2), 1 / sqrt(2)], [1 / sqrt(2), -1 / sqrt(2)]]))
cnot = operator(
    "CX", np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]))
q1 = state("q1", np.array([1, 0]))

## Circuit to implement entanglement

mycir = circuit()
mycir.add_state(q0)
mycir.add_state(q1)
mycir.add_gate(q0, hadamard)
mycir.add_gate(hadamard, cnot)
mycir.add_gate(q1, cnot)
print(mycir.export())

mycir.visualize()
res_state = mycir.execute_circuit()

res_state.evaluate_results()

print(res_state.nqubits)
print(res_state.get_results())
res_state.plot_results()
示例#17
0
def ac_analysis(circ, start, nsteps, stop, step_type, xop=None, mna=None,\
 AC=None, Nac=None, J=None, data_filename="stdout", verbose=3):
    """Performs an AC analysis of the circuit (described by circ).
	"""

    if data_filename == 'stdout':
        verbose = 0

    #check step/start/stop parameters
    if start == 0:
        printing.print_general_error("AC analysis has start frequency = 0")
        sys.exit(5)
    if start > stop:
        printing.print_general_error("AC analysis has start > stop")
        sys.exit(1)
    if nsteps < 1:
        printing.print_general_error("AC analysis has number of steps <= 1")
        sys.exit(1)
    if step_type == options.ac_log_step:
        omega_iter = utilities.log_axis_iterator(stop, start, nsteps)
    elif step_type == options.ac_lin_step:
        omega_iter = utilities.lin_axis_iterator(stop, start, nsteps)
    else:
        printing.print_general_error("Unknown sweep type.")
        sys.exit(1)

    tmpstr = "Vea =", options.vea, "Ver =", options.ver, "Iea =", options.iea, "Ier =", \
    options.ier, "max_ac_nr_iter =", options.ac_max_nr_iter
    printing.print_info_line((tmpstr, 5), verbose)
    del tmpstr

    printing.print_info_line(("Starting AC analysis: ", 1), verbose)
    tmpstr = "w: start = %g Hz, stop = %g Hz, %d steps" % (start, stop, nsteps)
    printing.print_info_line((tmpstr, 3), verbose)
    del tmpstr

    #It's a good idea to call AC with prebuilt MNA matrix if the circuit is big
    if mna is None:
        (mna, N) = dc_analysis.generate_mna_and_N(circ)
        del N
        mna = utilities.remove_row_and_col(mna)
    if Nac is None:
        Nac = generate_Nac(circ)
        Nac = utilities.remove_row(Nac, rrow=0)
    if AC is None:
        AC = generate_AC(circ, [mna.shape[0], mna.shape[0]])
        AC = utilities.remove_row_and_col(AC)

    if circ.is_nonlinear():
        if J is not None:
            pass
            # we used the supplied linearization matrix
        else:
            if xop is None:
                printing.print_info_line(
                    ("Starting OP analysis to get a linearization point...",
                     3),
                    verbose,
                    print_nl=False)
                #silent OP
                xop = dc_analysis.op_analysis(circ, verbose=0)
                if xop is None:  #still! Then op_analysis has failed!
                    printing.print_info_line(("failed.", 3), verbose)
                    printing.print_general_error(
                        "OP analysis failed, no linearization point available. Quitting."
                    )
                    sys.exit(3)
                else:
                    printing.print_info_line(("done.", 3), verbose)
            printing.print_info_line(("Linearization point (xop):", 5),
                                     verbose)
            if verbose > 4: xop.print_short()
            printing.print_info_line(("Linearizing the circuit...", 5),
                                     verbose,
                                     print_nl=False)
            J = generate_J(xop=xop.asmatrix(),
                           circ=circ,
                           mna=mna,
                           Nac=Nac,
                           data_filename=data_filename,
                           verbose=verbose)
            printing.print_info_line((" done.", 5), verbose)
            # we have J, continue
    else:  #not circ.is_nonlinear()
        # no J matrix is required.
        J = 0

    printing.print_info_line(("MNA (reduced):", 5), verbose)
    printing.print_info_line((str(mna), 5), verbose)
    printing.print_info_line(("AC (reduced):", 5), verbose)
    printing.print_info_line((str(AC), 5), verbose)
    printing.print_info_line(("J (reduced):", 5), verbose)
    printing.print_info_line((str(J), 5), verbose)
    printing.print_info_line(("Nac (reduced):", 5), verbose)
    printing.print_info_line((str(Nac), 5), verbose)

    sol = results.ac_solution(circ,
                              ostart=start,
                              ostop=stop,
                              opoints=nsteps,
                              stype=step_type,
                              op=xop,
                              outfile=data_filename)

    # setup the initial values to start the iteration:
    nv = len(circ.nodes_dict)
    j = numpy.complex('j')

    Gmin_matrix = dc_analysis.build_gmin_matrix(circ, options.gmin,
                                                mna.shape[0], verbose)

    iter_n = 0  # contatore d'iterazione
    #printing.print_results_header(circ, fdata, print_int_nodes=options.print_int_nodes, print_omega=True)
    printing.print_info_line(("Solving... ", 3), verbose, print_nl=False)
    tick = ticker.ticker(increments_for_step=1)
    tick.display(verbose > 1)

    x = xop
    for omega in omega_iter:
        (x, error, solved, n_iter) = dc_analysis.dc_solve(mna=(mna + numpy.multiply(j*omega, AC) + J), \
        Ndc=Nac,  Ntran=0, circ=circuit.circuit(title="Dummy circuit for AC", filename=None), Gmin=Gmin_matrix, x0=x, \
        time=None, locked_nodes=None, MAXIT=options.ac_max_nr_iter, skip_Tt=True, verbose=0)
        if solved:
            tick.step(verbose > 1)
            iter_n = iter_n + 1
            # hooray!
            sol.add_line(omega, x)
        else:
            break

    tick.hide(verbose > 1)

    if solved:
        printing.print_info_line(("done.", 1), verbose)
        ret_value = sol
    else:
        printing.print_info_line(("failed.", 1), verbose)
        ret_value = None

    return ret_value
import sys
sys.path.append("../")

from qutip import *
import matplotlib.pyplot as plt
import numpy as np
from circuit import circuit, hadamard, c_phase
from gates import cn_phase, c_not
from sim_py import sim_py

initial_state = 0  # 0 or 1
n_qbits = 1

i_state = basis(2, initial_state)
register = i_state

had = circuit()
had | hadamard(0)

sim = sim_py()
register = Qobj(sim.apply_circuit(had, register.full()))

b = Bloch()
b.add_states(i_state)
b.add_states(register)
b.show()
示例#19
0
#!/bin/python2
import sys
from circuit import circuit
#INPUT FNAME
f = open(sys.argv[1])
chromosome_string = f.readline()
f.close()
#REFERENCE FNAME
remove_nodes = int(sys.argv[2])
#OUTPUT FNAME
#filename = sys.argv[3]
f = open(sys.argv[3], 'w')

c = circuit(chromosome_string[:-1])
c.cols -= remove_nodes
def get_chrom(circuit):
    global remove_nodes
    chrom = circuit.circuit
    metadata = "{"+str(circuit.inputs)+"," +str(circuit.outputs)+","+str(circuit.cols)+"," +str(circuit.rows)+"," +str(circuit.node_inputs)+"," +str(circuit.node_outputs)+",333}"
    result = ""
    idx = circuit.inputs
    for gene in chrom[:-1]:
        result+="(["+str(idx)+"]"+str(gene[0])+","+str(gene[1])+","+str(circuit.GENE_TRANSLATION.index(gene[2]))+")"
        idx+=1
    for _ in xrange(idx - circuit.inputs, circuit.cols):
        result+="(["+str(idx)+"]0,0,0)"
        idx+=1
    result += "(" + reduce(lambda x,y: str(x)+","+str(y), chrom[-1]) + ")"
    return metadata+ result

chrom = get_chrom(c)
示例#20
0
fsg  = open(sys.argv[1].split('.')[0]+'.sg', 'w')


lpn = []
ckt = []

for line in flpn:    
	lpn.append(line)

for line in fckt:
	ckt.append(line)

graph_name = sys.argv[1].split('.')
print graph_name
SG = graph.graph(graph_name[0])
CKT = circuit.circuit(graph_name[0])
SG.CreateDSlpn(lpn)
getSG = SG.find_SG()
print "Message :", getSG[0]
if(len(getSG)>1):
	print "Hell0: ", getSG[4:7]
	func.writeSGfull(fsg, getSG)
	if(len(getSG[6]) !=0 ):
		fsgSpec = open(sys.argv[1].split('.')[0]+'.sgSpec', 'w')
		func.writeSGspec(fsgSpec, getSG)
		fsgSpec.close()
	fsg.close()
	CKT.createCircuit(ckt,SG.inputs,SG.outputs)
	###---------- Perform CGE verify ---------------####
	if(len(getSG[6]) !=0):
		fopen = open(sys.argv[1].split('.')[0]+'.sgSpec', 'r+')
示例#21
0
def main():

    hours = [744, 672, 744, 720, 744, 720, 744, 744, 720, 744, 720, 744]

    month = 9

    value = 0

    powerUsage = []

    modelUsage = []

    deltas = [0]
    # Uncomment below to run a simulation using different delta perameters
    # while(value < 3):
    #     deltas.append(value)
    #     value = value+0.5

    # Uncomment below to run a simulation using different time thresholds
    # timeThresh=[]
    # value=1
    # while(value < 10):
    #     timeThresh.append(value)
    #     value = value+0.5

    # power = [0.2]

    models = [1, 2, 3, 4]

    kVals = [15]
    pelt = []

    # Uncomment below to run a simulation using different temperature thresholds
    # thresh=10
    # kVals = []
    # while(thresh<15.5):
    #     kVals.append(thresh)
    #     thresh+=0.5
    # visualiseAllTemp()

    visualiseMultisim()

    for i in models:
        month = 9
        for delta in deltas:
            for k in kVals:

                # Change 0.2 to change the power of the Peltier device used
                fl = flask(i, k, delta, 0.2)

                with open("temp.csv") as f:  # Change to step.csv to view the step response
                    for temp in f:
                        fl.updateTemp(float(temp))
                        value = value + 1

                        if (value > hours[month % 12]):

                            circ = circuit(  # Calculates the monthly energy usage of the device
                                (fl.peltierTime/(60**2)), hours[month % 12])
                            powerUsage.append(circ.calculateTotalPower())
                            value = 0
                            month = (month+1)

                            fl.peltierTime = 0

                            # if((month % 12) == 2):            #Saves the time that the peltier is on during the worst month
                            #     pelt.append(fl.secondsOn)

                            fl.secondsOn = []

                # modelUsage.append(powerUsage)
                powerUsage = []

                # Uncomment below to visualise various aspects of the device, used in finding optimal perameters and viewing the device's functioning
                # Uncomment to stop visualising the flask's internal temperature during the simulation
                fl.visualisedata()
示例#22
0
文件: ac.py 项目: vovkd/ahkab
def ac_analysis(circ, start, nsteps, stop, step_type, xop=None, mna=None,\
	AC=None, Nac=None, J=None, data_filename="stdout", verbose=3):
	"""Performs an AC analysis of the circuit (described by circ).
	"""
	
	if data_filename == 'stdout':
		verbose = 0

	#check step/start/stop parameters
	if start == 0:
		printing.print_general_error("AC analysis has start frequency = 0")
                sys.exit(5)
	if start > stop:
		printing.print_general_error("AC analysis has start > stop")
		sys.exit(1)
	if nsteps < 1:
		printing.print_general_error("AC analysis has number of steps <= 1")
		sys.exit(1)
	if step_type == options.ac_log_step:
		omega_iter = utilities.log_axis_iterator(stop, start, nsteps)
	elif step_type == options.ac_lin_step:
		omega_iter = utilities.lin_axis_iterator(stop, start, nsteps)
	else:
		printing.print_general_error("Unknown sweep type.") 
		sys.exit(1)
	
	tmpstr = "Vea =", options.vea, "Ver =", options.ver, "Iea =", options.iea, "Ier =", \
	options.ier, "max_ac_nr_iter =", options.ac_max_nr_iter
	printing.print_info_line((tmpstr, 5), verbose)
	del tmpstr
	
	printing.print_info_line(("Starting AC analysis: ", 1), verbose)
	tmpstr = "w: start = %g Hz, stop = %g Hz, %d steps" % (start, stop, nsteps)
	printing.print_info_line((tmpstr, 3), verbose)
	del tmpstr

	#It's a good idea to call AC with prebuilt MNA matrix if the circuit is big
	if mna is None:
		(mna, N) = dc_analysis.generate_mna_and_N(circ)
		del N
		mna = utilities.remove_row_and_col(mna)
	if Nac is None:
		Nac = generate_Nac(circ)
		Nac = utilities.remove_row(Nac, rrow=0)
	if AC is None:
		AC = generate_AC(circ, [mna.shape[0], mna.shape[0]])
		AC = utilities.remove_row_and_col(AC)

	
	if circ.is_nonlinear():
		if J is not None:
			pass
			# we used the supplied linearization matrix
		else:
			if xop is None:
				printing.print_info_line(("Starting OP analysis to get a linearization point...", 3), verbose, print_nl=False)
				#silent OP
				xop = dc_analysis.op_analysis(circ, verbose=0)
				if xop is None: #still! Then op_analysis has failed!
					printing.print_info_line(("failed.", 3), verbose)
					printing.print_general_error("OP analysis failed, no linearization point available. Quitting.") 
					sys.exit(3)
				else:
					printing.print_info_line(("done.", 3), verbose)
			printing.print_info_line(("Linearization point (xop):", 5), verbose)
			if verbose > 4: xop.print_short()
			printing.print_info_line(("Linearizing the circuit...", 5), verbose, print_nl=False)
			J = generate_J(xop=xop.asmatrix(), circ=circ, mna=mna, Nac=Nac, data_filename=data_filename, verbose=verbose)
			printing.print_info_line((" done.", 5), verbose)
			# we have J, continue
	else: #not circ.is_nonlinear()
		# no J matrix is required.
		J = 0
	
	printing.print_info_line(("MNA (reduced):", 5), verbose)
	printing.print_info_line((str(mna), 5), verbose)
	printing.print_info_line(("AC (reduced):", 5), verbose)
	printing.print_info_line((str(AC), 5), verbose)
	printing.print_info_line(("J (reduced):", 5), verbose)
	printing.print_info_line((str(J), 5), verbose)
	printing.print_info_line(("Nac (reduced):", 5), verbose)
	printing.print_info_line((str(Nac), 5), verbose)
	
	sol = results.ac_solution(circ, ostart=start, ostop=stop, opoints=nsteps, stype=step_type, op=xop, outfile=data_filename)

	# setup the initial values to start the iteration:
	nv = len(circ.nodes_dict)
	j = numpy.complex('j')

	Gmin_matrix = dc_analysis.build_gmin_matrix(circ, options.gmin, mna.shape[0], verbose)

	iter_n = 0  # contatore d'iterazione
	#printing.print_results_header(circ, fdata, print_int_nodes=options.print_int_nodes, print_omega=True)
	printing.print_info_line(("Solving... ", 3), verbose, print_nl=False)
	tick = ticker.ticker(increments_for_step=1)
	tick.display(verbose > 1)

	x = xop
	for omega in omega_iter:
		(x, error, solved, n_iter) = dc_analysis.dc_solve(mna=(mna + numpy.multiply(j*omega, AC) + J), \
		Ndc=Nac,  Ntran=0, circ=circuit.circuit(title="Dummy circuit for AC", filename=None), Gmin=Gmin_matrix, x0=x, \
		time=None, locked_nodes=None, MAXIT=options.ac_max_nr_iter, skip_Tt=True, verbose=0)
		if solved:
			tick.step(verbose > 1)
			iter_n = iter_n + 1
			# hooray!
			sol.add_line(omega, x)
		else:
			break
	
	tick.hide(verbose > 1)
	
	if solved:
		printing.print_info_line(("done.", 1), verbose)
		ret_value = sol
	else:
		printing.print_info_line(("failed.", 1), verbose)
		ret_value =  None
	
	return ret_value
示例#23
0
        json = 0

    if json == 1:
        # take json input and convert to object
        params = jsonmod.loads(query_string)
        updatecontroller = controller.controller([])
        for i in params.keys():
            if i == "spasettemp":
                updatecontroller.setspasettemp(params[i])
            elif i == "poolsettemp":
                updatecontroller.setpoolsettemp(params[i])
            elif i == "airtemp":
                updatecontroller.setairtemp(params[i])
            elif i[:7] == "circuit":  # build circuit
                cir = circuit.circuit(i[7:], params[i]['name'],
                                      params[i]['byte'], params[i]['bit'],
                                      params[i]['value'])
                updatecontroller.appendcircuit(cir)
            elif i == "token":
                updatecontroller.setpassword(params[i])
            else:
                # nothing, ignore
                a = 1
    else:
        # take input and convert to object
        if 'query_string' in globals():
            params = dict(cgi.parse_qsl(query_string))
        else:
            params = {}

        # if a key does not exist, then we will assume it is a "0"
示例#24
0
from circuit import circuit
from PIL import Image, ImageDraw
from os import listdir
from os.path import isfile, join

# perform circuit initialization
# TODO
circuit = circuit()

# make picture
height = 1200
width = 1200

deltay = height / 12
deltax = width / 12

circlex = deltax / 5
circley = deltay / 3

radius = circlex / 3

directory = "./Routing/output/"

fnames = [s for s in listdir(directory) if ".txt" in s]
for fname in fnames:
    print fname
    with open(join(directory, fname)) as f:
        image = Image.new('RGB', size=(height, width), color='white')
        draw = ImageDraw.Draw(image)

        fill = 128
示例#25
0
 def nots():
     a = circuit()
     for i in range(self._n_qbits):
         if (reflection_dir & (1 << i)) == 0:
             a | self._not_gate(i)
     return a
示例#26
0
文件: tswitch.py 项目: amalagon/ahkab
import ahkab
import switch, circuit, printing
mycircuit = circuit.circuit(title="Test switch")
gnd = mycircuit.get_ground_node()
mycircuit.add_resistor("R1", "n1", gnd, 1e3)
mycircuit.add_resistor("R2", "n2", "n3", 50)
mycircuit.add_model("sw", "mysw", {'name':"mysw", 'VT':6, 'VH':1., 'RON':100., 'ROFF':None})
mycircuit.add_switch('SW1', 'n2', gnd, 'n1', gnd, ic=True, model_label='mysw')
mycircuit.add_isource('I1', 'n1', gnd, 1e-3)
mycircuit.add_vsource('V1', 'n3', gnd, 1.)
printing.print_circuit(mycircuit)
opa = {'type':'op', 'guess_label':None, 'guess':False}
ahkab.process_analysis([opa], mycircuit, '/tmp/out.data', 6)
示例#27
0
def parse_circuit(filename, read_netlist_from_stdin=False):
	"""Parse a SPICE-like netlist and return a circuit instance 
	that includes all components, all nodes known
	with that you can recreate mna and N at any time.
	Note that solving the circuit requires accessing to the elements in 
	the circuit instance to evaluate non linear elements' currents.
	
	Directives are collected in a list and returned too, except for
	subcircuits, those are added to circuit.subckts_dict.
	
	Returns:
	(circuit_instance, directives)
	"""
	# Lots of differences with spice's syntax:
	# Support for alphanumeric node names, but the ref has to be 0. always
	# Do not break lines with + 
	# .end is not required, but if is used anything following it is ignored
	# many others, see doc.
	
	circ = circuit.circuit(title="", filename=filename)
	
	if not read_netlist_from_stdin:
		ffile = open(filename, "r")
	else:
		ffile = sys.stdin
		
	file_list = [(ffile, "unknown", not read_netlist_from_stdin)]
	file_index = 0
	directives = []
	model_directives = []
	postproc = []
	subckts_list_temp = []
	netlist_lines = []
	current_subckt_temp = []
	within_subckt = False
	line_n = 0
	
	try:
		while ffile is not None:
			for line in ffile:
				line_n = line_n + 1
				
				line = line.strip().lower()
				if line_n == 1:
					# the first line is always the title
					circ.title = line
					continue
				elif len(line) == 0:
					continue #empty line
				elif line[0] == "*": # comments start with *
					continue
				
				# directives are grouped together and evaluated after
				# we have the whole circuit.
				# subcircuits are grouped too, but processed first
				if line[0] == ".":
					line_elements = line.split()
					if line_elements[0] == '.subckt':
						if within_subckt:
							raise NetlistParseError, "nested subcircuit declaration detected"
						current_subckt_temp = current_subckt_temp + [(line, line_n)]
						within_subckt = True
					elif line_elements[0] == '.ends':
						if not within_subckt:
							raise NetlistParseError, "corresponding .subckt not found"
						within_subckt = False
						subckts_list_temp.append(current_subckt_temp)
						current_subckt_temp = []
					elif line_elements[0] == '.include':
						file_list.append(parse_include_directive(line, line_elements=None))
					elif line_elements[0] == ".end":
						break
					elif line_elements[0] == ".plot":
						postproc.append((line, line_n))
					elif line_elements[0] == ".model":
						model_directives.append((line, line_n))
					else:
						directives.append((line, line_n))
					continue
				
				if within_subckt:
					current_subckt_temp  = current_subckt_temp + [(line, line_n)]
				else:
					netlist_lines = netlist_lines + [(line, line_n)]
			if within_subckt:
				raise NetlistParseError, ".ends not found"
			
			file_index = file_index + 1
			ffile = get_next_file_and_close_current(file_list, file_index)
			#print file_list
			
	except NetlistParseError, (msg,):
		if len(msg):
			printing.print_general_error(msg)
		printing.print_parse_error(line_n, line)
		#if not read_netlist_from_stdin:
			#ffile.close()
		sys.exit(45)