예제 #1
0
def linerating_consfcn(x, c):
    const = Const()

    nb  = c.bus.shape[0]
    ng  = c.gen.shape[0]
    nbr = c.branch.shape[0]

    ii       = get_var_idx(c)
    va_idx   = np.array(range(ii['i1']['va'], ii['iN']['va']), dtype=int)
    vm_idx   = np.array(range(ii['i1']['vm'], ii['iN']['vm']), dtype=int)
    fbus_idx = np.array(c.branch[:, const.F_BUS] - 1, dtype=int)
    tbus_idx = np.array(c.branch[:, const.T_BUS] - 1, dtype=int)
    x_idx    = np.concatenate((va_idx, vm_idx))

    va    = x[va_idx]
    vm    = x[vm_idx]
    vcplx = vm * np.exp(1j * va)

    _, Yf, Yt = makeYbus(c)

    flow_max = (c.branchrate / c.mva_base ) ** 2
    Sf = vcplx[fbus_idx] * np.conj(Yf * vcplx)
    St = vcplx[tbus_idx] * np.conj(Yf * vcplx)
    
    Sfreal_sq = np.real(Sf) ** 2
    Sfimag_sq = np.imag(Sf) ** 2
    Streal_sq = np.real(St) ** 2
    Stimag_sq = np.imag(St) ** 2

    return - np.concatenate((Sfreal_sq + Sfimag_sq - flow_max, \
                           Streal_sq + Stimag_sq - flow_max))
예제 #2
0
    def q_conv_tot(self):
        # Total convection loss, W
        average_temperature = (self.airPipe.temperature +
                               self.amb.temperature) / 2
        # Film temperature is used
        k = PropsSI('L', 'T', average_temperature, 'P', self.amb.pressure,
                    self.amb.fluid)

        beta = PropsSI('ISOBARIC_EXPANSION_COEFFICIENT', 'T',
                       average_temperature, 'P', self.amb.pressure,
                       self.amb.fluid)
        mu = PropsSI('V', 'T', average_temperature, 'P', self.amb.pressure,
                     self.amb.fluid)
        density = PropsSI('D', 'T', average_temperature, 'P',
                          self.amb.pressure, self.amb.fluid)
        nu = mu / density
        Gr = Const.G * beta * (self.airPipe.temperature - self.amb.temperature) * \
            self.d_bar_cav ** 3 / nu ** 2

        Nu = Const.Nu_nat_conv(Gr, self.airPipe.temperature,
                               self.amb.temperature, self.theta, self.d_ap,
                               self.d_bar_cav)
        h_nat = k * Nu / self.d_bar_cav

        h_for = 0.1967 * self.amb.wind_speed**1.849

        return (h_nat + h_for) * self.A_cav * (self.airPipe.temperature -
                                               self.amb.temperature)
예제 #3
0
def dSbr_dV(branch, Yf, Yt, V):
    const = Const()

    nb  = V.shape[0]
    nbr = branch.shape[0]

    b_idx    = np.array(range(nb), dtype=int)
    br_idx   = np.array(range(nbr), dtype=int)
    fbus_idx = np.array(branch[:, const.F_BUS] - 1, dtype=int)
    tbus_idx = np.array(branch[:, const.T_BUS] - 1, dtype=int)

    Vnorm = V / np.abs(V)
    If    = Yf.dot(V)
    It    = Yt.dot(V)
    Sf    = V[fbus_idx] * np.conj(If)
    St    = V[tbus_idx] * np.conj(It)

    diagVf    = csr_matrix((V[fbus_idx], (br_idx, br_idx)), shape=(nbr, nbr))
    diagIf    = csr_matrix((If, (br_idx, br_idx)), shape=(nbr, nbr))
    diagVt    = csr_matrix((V[tbus_idx], (br_idx, br_idx)), shape=(nbr, nbr))
    diagIt    = csr_matrix((It, (br_idx, br_idx)), shape=(nbr, nbr))
    diagV     = csr_matrix((V, (b_idx, b_idx)), shape=(nb, nb))
    diagVnorm = csr_matrix((Vnorm, (b_idx, b_idx)), shape=(nb, nb))

    Cvf     = csr_matrix((V[fbus_idx], (br_idx, fbus_idx)), shape=(nbr, nb))
    Cvt     = csr_matrix((V[tbus_idx], (br_idx, tbus_idx)), shape=(nbr, nb))
    Cvnormf = csr_matrix((Vnorm[fbus_idx], (br_idx, fbus_idx)), shape=(nbr, nb))
    Cvnormt = csr_matrix((Vnorm[tbus_idx], (br_idx, tbus_idx)), shape=(nbr, nb))

    dSf_dVa = (1j) * ( np.conj(diagIf) * Cvf - diagVf * np.conj(Yf * diagV) )
    dSt_dVa = (1j) * ( np.conj(diagIt) * Cvt - diagVt * np.conj(Yt * diagV) ) 
    dSf_dVm = diagVf * np.conj(Yf * diagVnorm) + np.conj(diagIf) * Cvnormf
    dSt_dVm = diagVt * np.conj(Yt * diagVnorm) + np.conj(diagIt) * Cvnormt

    return dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St
예제 #4
0
def linerating_consfcn_jac(x, c):
    const = Const()

    nb  = c.bus.shape[0]
    ng  = c.gen.shape[0]
    nbr = c.branch.shape[0]
    nx  = 2 * (nb + ng)

    ii       = get_var_idx(c)
    va_idx   = np.array(range(ii['i1']['va'], ii['iN']['va']), dtype=int)
    vm_idx   = np.array(range(ii['i1']['vm'], ii['iN']['vm']), dtype=int)
    fbus_idx = np.array(c.branch[:, const.F_BUS] - 1, dtype=int)
    tbus_idx = np.array(c.branch[:, const.T_BUS] - 1, dtype=int)
    x_idx    = np.concatenate((va_idx, vm_idx))

    va    = x[va_idx]
    vm    = x[vm_idx]
    vcplx = vm * np.exp(1j * va)

    _, Yf, Yt = makeYbus(c)

    br_idx   = np.array(range(0, nbr), dtype=int)
    fbus_idx = np.array(c.branch[:, const.F_BUS] - 1, dtype=int)
    tbus_idx = np.array(c.branch[:, const.T_BUS] - 1, dtype=int)

    dFf_dVa, dFf_dVm, dFt_dVa, dFt_dVm, Ff, Ft = dSbr_dV(c.branch, Yf, Yt, vcplx)
    df_dVa, df_dVm, dt_dVa, dt_dVm = dAbr_dV(dFf_dVa, dFf_dVm, dFt_dVa, dFt_dVm, Ff, Ft)

    dh = lil_matrix((2*nbr, nx), dtype=float)
    dh[:, x_idx] = vstack((hstack((df_dVa, df_dVm)),hstack((dt_dVa, dt_dVm))))

    return -dh.toarray()
예제 #5
0
def polycost_hess(cost_metrics, pg):
    const = Const()
    cost = 0.
    pn = int(cost_metrics[const.NCOST])
    for pi in range(2, pn):
        cost += pi * cost_metrics[-(1+pi)] * pg ** (pi - 2)

    return cost
예제 #6
0
def polycost(cost_metrics, pg):
    const = Const()
    cost = 0.
    pn = int(cost_metrics[const.NCOST])
    for pi in range(pn):
        cost += cost_metrics[-(1+pi)] * pg ** pi
    
    return cost
예제 #7
0
 def initData(self):
     dict = {}
     c = Const.Const()
     if self.flag == False:
         dict = c.test
     else:
         dict = c.online
     self.dict = dict
예제 #8
0
파일: Ressource.py 프로젝트: daureg/Ivory
	def change_val(self, value):
		"""Modify the value of the ressource."""
		self.val = Const.clamp(self.val + value, 0, Const.RESSOURCE_VICTORY)
		self.val_text = self.val_font.render("%d %s"%(self.val, self.desc),
				True, (255, 255, 255))
		if value > 0:
			self.pos_sound.play()
		if value < 0:
			self.neg_sound.play()
예제 #9
0
 def change_val(self, value):
     """Modify the value of the ressource."""
     self.val = Const.clamp(self.val + value, 0, Const.RESSOURCE_VICTORY)
     self.val_text = self.val_font.render("%d %s" % (self.val, self.desc),
                                          True, (255, 255, 255))
     if value > 0:
         self.pos_sound.play()
     if value < 0:
         self.neg_sound.play()
예제 #10
0
 def train(load_text_fname, save_fname, saveflag="save"):
     word_feat_len = Const.Const().word_feat_len
     print("train word2vec")
     sentences = gensim.models.word2vec.Text8Corpus(load_text_fname)
     #model = gensim.models.word2vec.Word2Vec(sentences, size=200, window=5, workers=4, min_count=5)
     model = gensim.models.word2vec.Word2Vec(
         sentences, size=word_feat_len, window=5, workers=4, min_count=1, hs=1)
     if saveflag == "save":
         print("save " + save_fname)
         model.save(save_fname)
예제 #11
0
def cartesian_to_geodetic(point , jd):
    
    #Determine angle between the vernal equinox and the Greenwhich Meridian
    UT = m.fmod(jd + 0.5, 1.0)
    T = (jd - UT - 2451545.0) / 36525.0;
    omega = 1.0 + 8640184.812866 / 3155760000.0;
    gmst0 = 24110.548412 + T * (8640184.812866 + T * (0.093104 - T * 6.2E-6));
    theta_GMST = m.fmod(gmst0 + 86400.0 * omega * UT, 86400.0) * 2 * m.pi / 86400.0;
    
    #Setup coordinates to better illustrate calculations
    x , y , z = point[0] , point[1] , point[2]
    e = 0.081819190842622
    a = 6378.137  #Earths semi major axis
    
    #Calculate the geodetic longitude(radians)
    longitude = m.fmod( (m.atan2(y , x) - theta_GMST) , 2*m.pi)   
    
    #Calculate the geodetic latitude using an iterative method(radians)    
    latitude = m.atan2( z , m.sqrt(x*x + y*y))
     
    iters = 0
    latitudeOld = latitude
     
    while( (m.fabs(latitude - latitudeOld) < 1.0e-10) or iters == 0):   
    
         latitudeOld = latitude
         c = a * e * e * m.sin(latitudeOld) / m.sqrt( 1.0 - e * e * m.sin(latitudeOld) * m.sin(latitudeOld))
         latitude = m.atan2( ( z + c ) , m.sqrt(x*x + y*y) )
         iters = iters + 1
    
     
    print "Iterations needed for answers => " , iters
    
    
    altitude = m.sqrt(x*x + y*y)/m.cos(latitude) - a/m.sqrt(1 - e*e*m.sin(latitude)*m.sin(latitude))
    
    print "Longitude" , C.r2d(longitude)
    print "Latitude" , C.r2d(latitude)
    print "altitude" , altitude
    
    return latitude , longitude , altitude
예제 #12
0
    def q_dr_1_2(self):
        #  Heat transferred from the air pipe to the air, W
        average_temperature = (self.st_i.temperature +
                               self.st_o.temperature) / 2
        average_pressure = (self.st_i.pressure + self.st_o.pressure) / 2
        density = PropsSI('D', 'T', average_temperature, 'P', average_pressure,
                          self.st_i.fluid)
        v = 4 * self.st_i.flow_rate[0] / (np.pi * self.airPipe.d_i**2 *
                                          density)
        mu = PropsSI('V', 'T', average_temperature, 'P', average_pressure,
                     self.st_i.fluid)
        re = density * v * self.airPipe.d_i / mu
        cp = PropsSI('C', 'T', average_temperature, 'P', average_pressure,
                     self.st_i.fluid)
        k = PropsSI('L', 'T', average_temperature, 'P', average_pressure,
                    self.st_i.fluid)
        pr = cp * mu / k
        mu_cav = PropsSI('V', 'T', self.airPipe.temperature, 'P',
                         average_pressure, self.st_i.fluid)
        Nu_prime = Const.Nu_in_pipe(re, pr, mu, mu_cav)

        c_r = 1 + 3.5 * self.airPipe.d_i / (self.d_cav - self.airPipe.d_i -
                                            2 * self.airPipe.delta_a)
        Nu = c_r * Nu_prime

        h = Nu * k / self.airPipe.d_i

        H_prime_c = self.airPipe.d_i + 2 * self.airPipe.delta_a
        N = np.floor(self.dep_cav / H_prime_c)
        H_c = self.dep_cav / N
        L_c = N * np.sqrt((np.pi * self.d_cav)**2 + H_c**2)
        A_airPipe = np.pi * self.airPipe.d_i * L_c

        DeltaT1 = self.airPipe.temperature - self.st_i.temperature
        DeltaT2 = self.airPipe.temperature - self.st_o.temperature
        DeltaT = Const.log_mean(DeltaT1, DeltaT2)

        return h * A_airPipe * DeltaT
예제 #13
0
def makeSbus(mva_base, bus, gen):
    const = Const()

    nb = bus.shape[0]
    ng = gen.shape[0]

    g_idx = np.array(range(ng), dtype=int)
    g_busnum = np.array(gen[:, const.GEN_BUS] - 1, dtype=int)

    Sbusg = np.ones(nb) * (0 + 0j)
    Sbusg[g_busnum] = (gen[:, const.PG] + 1j * gen[:, const.QG]) / mva_base
    Sbusd = (bus[:, const.PD] + 1j * bus[:, const.QD]) / mva_base
    
    return Sbusg - Sbusd
예제 #14
0
def main():
    rtds_cmd_adapter = RtdsCmdAdapter({"ip": "192.168.1.104", "port": 4575})
    rtds_cmd_adapter.connect_rtds()

    c37118_data_adapter = C37118InputDataAdapter()
    c37118_data_adapter.add_connection({
        "ip": "192.168.1.111",
        "port": 4712,
        "id": 1
    })
    c37118_data_adapter.add_connection({
        "ip": "192.168.1.111",
        "port": 4722,
        "id": 2
    })
    c37118_data_adapter.connect_pmu()
    c37118_data_adapter.close()

    frame = c37118_data_adapter.get_pmu_measurements()
    currentPg = calculatePg(frame)
    pprint(frame)
    print(currentPg)

    const = Const()
    casepath = './case14mod/'
    c = Case()
    c.import_case(casepath)
    c.set_gen_prop(const.PMAX, [1, 2, 3], currentPg[1:4])
    #     c.set_gen_prop(const.PMAX, [1,2,3], [40.05814367749094, 70.12544088354686, 78.47923733719254])
    #     c.set_branch_prop('RATE', [14], [34.999])
    c.scale_branch_prop([const.BR_R, const.BR_X], multi=1.0)

    for i in range(0, 100):
        start_time = time.time()
        res = opf.runcopf(c, flat_start=False)
        end_time = time.time()
        print("Optimal Outputs: %s" % str(res['PG']))
        print('Optimization execution time: %.8f' % (end_time - start_time))

        if res['PG'][2] < 0.99 * currentPg[2]:
            rtds_cmd_adapter.send_cmd('SetSlider "SL3" = %.4f;' %
                                      (res['PG'][2] / 100))

    rtds_cmd_adapter.close()
예제 #15
0
def acpf_consfcn_jac(x, c):
    const = Const()

    nb  = c.bus.shape[0]
    ng  = c.gen.shape[0]
    nbr = c.branch.shape[0]
    nx  = 2 * (nb + ng)

    ii       = get_var_idx(c)
    g_idx    = np.array(range(0, ng), dtype=int)
    gbus_idx = np.array(c.gen[:, const.GEN_BUS] - 1, dtype=int)
    cons_idx = np.array(range(2 * nb), dtype=int)
    va_idx   = np.array(range(ii['i1']['va'], ii['iN']['va']), dtype=int)
    vm_idx   = np.array(range(ii['i1']['vm'], ii['iN']['vm']), dtype=int)
    pg_idx   = np.array(range(ii['i1']['pg'], ii['iN']['pg']), dtype=int)
    qg_idx   = np.array(range(ii['i1']['qg'], ii['iN']['qg']), dtype=int)
    x_idx    = np.concatenate((va_idx, vm_idx, pg_idx, qg_idx))

    va = x[va_idx]
    vm = x[vm_idx]
    pg = x[pg_idx]
    qg = x[qg_idx]

    vcplx = vm * np.exp(1j * va)
    c.gen[:, const.PG] = c.mva_base * pg
    c.gen[:, const.QG] = c.mva_base * qg

    Ybus, _, _ = makeYbus(c)
    Sbus = makeSbus(c.mva_base, c.bus, c.gen)

    dSdVa, dSdVm = dSbus_dV(Ybus, vcplx)
    dSdV = hstack((dSdVa, dSdVm))
    neg_Cg = csr_matrix((-np.ones(ng), (gbus_idx, g_idx)), shape=(nb, ng))
    zeros_b_g = csr_matrix(([],([],[])), shape=(nb, ng))

    dpinj = hstack((csr_matrix(np.real(dSdV.toarray())), neg_Cg, zeros_b_g))
    dqinj = hstack((csr_matrix(np.imag(dSdV.toarray())), zeros_b_g, neg_Cg))

    dg = lil_matrix((2*nb, nx), dtype=float)
    dg[:, x_idx] = vstack((dpinj, dqinj))

    return dg.toarray()
예제 #16
0
    def q_cond_conv(self):
        # Convection loss from the insulating layer, W
        mu = PropsSI('V', 'T', self.amb.temperature, 'P', self.amb.pressure,
                     self.amb.fluid)
        density = PropsSI('D', 'T', self.amb.temperature, 'P',
                          self.amb.pressure, self.amb.fluid)
        nu = mu / density
        d_o = self.insLayer.d_i + 2 * self.insLayer.delta
        Re = self.amb.wind_speed * d_o / nu

        Cp = PropsSI('C', 'T', self.amb.temperature, 'P', self.amb.pressure,
                     self.amb.fluid)
        k = PropsSI('L', 'T', self.amb.temperature, 'P', self.amb.pressure,
                    self.amb.fluid)
        Pr = Cp * mu / k

        Nu = Const.Nu_of_external_cylinder(Re, Pr)

        h = Nu * k / d_o
        A_ins = self.A_ins
        return h * A_ins * (self.insLayer.temperature - self.amb.temperature)
예제 #17
0
def makeYbus(c):
    const = Const()

    nb = c.bus.shape[0]
    ng = c.gen.shape[0]
    nbr = c.branch.shape[0]

    Ys = 1 / (c.branch[:, const.BR_R] + 1j * c.branch[:, const.BR_X])
    Bc = c.branch[:, const.BR_B]
    tap = np.ones(nbr)
    tap_idx = (c.branch.take(const.TAP, axis=1) != 0).nonzero()
    tap[tap_idx] = c.branch[tap_idx, const.TAP]

    Ytt = Ys + 1j * Bc/2
    Yff = Ytt / (tap * np.conj(tap))
    Yft = - Ys / np.conj(tap)
    Ytf = - Ys / tap

    ysh = (c.bus[:, const.GS] + 1j * c.bus[:, const.BS]) / c.mva_base

    b_idx = np.array(range(nb), dtype=int)
    br_idx = np.array(range(nbr), dtype=int)
    fbus_idx = np.array(c.branch[:, const.F_BUS] - 1, dtype=int)
    tbus_idx = np.array(c.branch[:, const.T_BUS] - 1, dtype=int)

    Cf = csr_matrix((np.ones(nbr), (br_idx, fbus_idx)), shape=(nbr,nb))
    Ct = csr_matrix((np.ones(nbr), (br_idx, tbus_idx)), shape=(nbr,nb))


    Yf = csr_matrix((np.concatenate((Yff, Yft)), \
                     (np.concatenate((br_idx, br_idx)), np.concatenate((fbus_idx, tbus_idx)))), \
                    shape=(nbr,nb))
    Yt = csr_matrix((np.concatenate((Ytf, Ytt)), \
                     (np.concatenate((br_idx, br_idx)), np.concatenate((fbus_idx, tbus_idx)))), \
                    shape=(nbr,nb))
    Ysh = csr_matrix((ysh, (b_idx, b_idx)), shape=(nb,nb))

    Ybus = Cf.T * Yf + Ct.T * Yt + Ysh
    
    return Ybus, Yf, Yt
  def __init__(self, parent, barre, n_case):
    self.parent = parent
    #tab = parent.active_tab
    #self.drawing = tab.active_drawing
    #id_study = self.drawing.id_study
    #study = parent.studies[id_study]
    self.rdm = parent.rdm
    self.unit_conv = Const.default_unit()
    self.status = 4

    self.Char = self.rdm.GetCharByNumber(n_case)
    self.barre = barre
    self.xml = Gtk.glade.XML("glade/pyBar.glade", "window3")
    self.window3 = self.xml.get_widget("window3")
    self._ini_window()
    self.combobox = self.xml.get_widget("w3_comboboxentry1") 
    self._combobox_regen()
    self.combo_barre_active()
    self.xml.signal_autoconnect({
	"on_w3_button1_clicked" : self._destroy, 
	"on_w3_button2_clicked" : self._export, 
	"on_w3_combobox_changed" : self._barre_changed,# executé au constructeur
	"on_window3_destroy" : self._window_destroy, 
	"on_w3_checkbutton1" : self._change_unit,
        "on_w3_configure_event" : self._configure_event
	#"on_w3_spinbutton1" : self._get_point_value
		})
    self.area = self.xml.get_widget("w3_drawingarea")
    #self.w, self.h = 300, 300
    #self.area.set_size_request(300, 300)
    self.area.connect("expose-event", self._expose_event)
    style = self.area.get_style()
    self.gc = style.fg_gc[Gtk.StateType.NORMAL]
    self._chart = classResuParBarre.SigmaDraw(self.area)

    # connexion du bouton 
    button = self.xml.get_widget("spinbutton1")
    button.connect('changed', self._get_point_value)
    self._get_point_value()
예제 #19
0
    def out_map(self, df, x, y, v):

        const = Const.Const()

        rx = list(df[x])
        ry = list(df[y])
        rssi = list(df[v])
        #print('The number of mesh =', len(rssi))
        for i in range(0, const.AREA[const.AREA_INDEX][4]):
            for j in range(0, const.AREA[const.AREA_INDEX][5]):
                #REM内の存在しないメッシュコードの補充
                #どちらか一方でも存在しないメッシュコードが存在しないとき補充
                if (i in rx) & (j in ry) == False:
                    rx.append(i)
                    ry.append(j)
                    rssi.append(0.0)

        tmp = pd.DataFrame({
            'X':rx,
            'Y':ry,
            'rssi':rssi
        })

        #matplotの設定
        plt.style.use('ggplot') 
        font = {'family' : 'meiryo'}
        matplotlib.rc('font', **font)
        plt.rcParams["font.size"] = 24

        piv = tmp.pivot_table(index='X', columns='Y', values='rssi', dropna= False)
        print('piv.shape =',piv.shape)

        plt.figure()
        sns.heatmap(piv,cmap = 'jet',linewidths=0.5, linecolor='Black',square = True,\
            cbar_kws={"orientation": "horizontal"})
        plt.xlabel('latitude')
        plt.ylabel('longitude')
        plt.show()
예제 #20
0
def parse_command(user_command: str, mem_challenger: MemoryChallenger) -> Const.STATUS:
    new_length = Validators.validate_format_regex_length(Const.COMMAND.CHANGE_LENGTH.value, user_command)
    if new_length is not None:
        mem_challenger.set_seq_length(new_length)
    else:
        try:
            user_command_enum = Const.COMMAND(user_command)
        except ValueError:
            print(admin_message(f"The command {user_command} is unknown. Please try to use one of the following"
                                f" commands: {Const.LIST_COMMANDS}"))
            return Const.STATUS.UNDEFINED_ACTION

        if user_command_enum in Const.QUIT_COMMANDS_LIST:
            return Const.STATUS.QUIT
        elif user_command_enum in Const.NEXT_COMMANDS_LIST:
            return Const.STATUS.NEXT
        elif user_command_enum == Const.COMMAND.CHANGE_LANGUAGE:
            mem_challenger.change_language()
        elif user_command_enum == Const.COMMAND.CHANGE_SORTED:
            mem_challenger.change_sorted()

    print(admin_message(f"The command '{user_command}' was executed."))
    return Const.STATUS.DONE_ACTION
예제 #21
0
def acpf_consfcn(x, c):
    const = Const()

    nb = c.bus.shape[0]
    ng = c.gen.shape[0]
    nbr = c.branch.shape[0]

    ii = get_var_idx(c)
    va = x[ii['i1']['va']:ii['iN']['va']]
    vm = x[ii['i1']['vm']:ii['iN']['vm']]
    pg = x[ii['i1']['pg']:ii['iN']['pg']]
    qg = x[ii['i1']['qg']:ii['iN']['qg']]

    vcplx = vm * np.exp(1j * va)
    c.gen[:, const.PG] = c.mva_base * pg
    c.gen[:, const.QG] = c.mva_base * qg

    Ybus, _, _ = makeYbus(c)
    Sbus = makeSbus(c.mva_base, c.bus, c.gen)
    mis = - Sbus + \
          vcplx * np.asarray(np.conj(Ybus * np.matrix(vcplx).T)).flatten() 

    return np.concatenate((np.real(mis), np.imag(mis)))
예제 #22
0
    def prepare(self):
        Const.log("URLID " + str(self.url_id))
        Const.log("BESTTERM " + self.bestterm)
        if(self.snippet == "" and not self.bestterm == ""):
            Const.log("in if")
            filename = Const.PGFOLDER + str(self.url_id)
            ucfile = None
            with open(filename, 'r') as myfile:
                Const.log("File open")
                entirefile = myfile.read()
                ucfile = unicode(entirefile, 'utf-8').lower()


	    anIndex=0
	    look=True
	    while(look):
	
	        anIndex = ucfile.find(self.bestterm, anIndex+1)
	        Const.log("Find ind " + str(anIndex))
	        if(not anIndex == -1):
	            start = max(anIndex-RANGE, 0)
	            Const.log("START : " + str(start))
	            end = min(len(ucfile), anIndex + RANGE)
	            Const.log("END : " + str(end))
	            rng = end - start
    	            Const.log("RNG : " + str(rng))
	            self.snippet = ucfile[start:end]
	            Const.log("SNIPPET : " + self.snippet)
		    look=check(self.snippet)
	        else:
		    look=False
		    self.snippet=''
예제 #23
0
def generate_TLE_set(alt , incl , meanAno , raan , argOfPeri , ecco , n , epoch_yr , epoch_days):
   
    #Define the first string   
    s = "1"
    s = s + ' ' + "25544U" #Satellite number - unused
    s = s + ' ' + "98067A   " #Launch Information - not used
    
    #Use "2013/01/01 00:00:00" as the reference epoch
    s = s +  str(epoch_yr) + str(epoch_days)
    s = s + " -.00002182" #First derivative of mean motion - hopefully unimportant
    s = s + "  00000-0 "
    s = s + "-00000-0" #B-Star Drag Term - Zeroed
    s = s + " 0"
    s = s + "  292" #Element Set Number
    s = s + "7" #Checksum 
    
    l1 = s
    
    print l1
    
    s = "2"
    s = s + " 25544 " #Append Satellite Number
    
    #Must be of format NNN.NNNN
    c = "{0:.4f}".format(C.r2d(incl)).rstrip("0") 
    
    print "c for incl" , c
    
    while( len(c) != 8):
       if(len(c) > 4 and c[3] != '.'):
           c = "0" + c
       else:
           c = c + "0"
    
    
    s = s + c
    s = s + " "
    
    c = "{0:.4f}".format(C.r2d(raan)).rstrip("0")
    
    print 'c for raan' , c
    
    while( len(c) != 8):
       if(len(c) > 4 and c[3] != '.'):
           c = "0" + c
       else:
           c = c + "0"
    
    
    s = s + c
 
    
    '''
    while( len(e) != 8):
       if(len(e) > 6 and e[3] != '.'):
           e = '0' + e
           e.replace(" " , '0')
           e.replace(" " , "")
       else:
           e = e + "0"
    e.replace(' ' , '0')
    
    
    l = len(c)
    for x in xrange(0 , l):
        if c[x] == '.':
            i = x
        
        
    for x in xrange(0 ,4 - i):
    
        c = '%d%s'  % (0, c)

    
    #Must be of format NNN.NNNN    
    while( len(c) <= 9):
           c = c + str(0) 
    '''

          
  
    
    c = str(int(ecco*m.pow(10,7))) 
    
    if(len(c) != 7):
        
        c = c.zfill(7)
        
    s = s + " " +  c + " "
    
    c = "{0:4f}".format(C.r2d(argOfPeri)).rstrip("0")  
    
    while( len(c) != 8):
       if(len(c) > 4 and c[3] != '.'):
           c = "0" + c
       else:
           c = c + "0"
    
    
    
    
    s = s + c
    
    c = " {0:4f}".format((meanAno)).rstrip("0")
    
    while( len(c) != 9):
           c = c + "0"
    
    
    s = s + c
    
    c = "{0:10f}".format(n)
    
    while( len(c) != 12):
           c = c + "0"
    
    s = s + c
    s = s + "56353" #Revolution Number - not used
    s = s + "7" #Checksum
    
    l2 = s
    
    print l2
    
    return l1 , l2
        
    
    
    
예제 #24
0
 def constraints(self, x):       
     const = Const() 
     ii = get_var_idx(self.case)
     tload = sum(self.case.bus[:,const.PD]) / self.case.mva_base
     return sum(x[ii['i1']['pg']:ii['iN']['pg']]) - tload
예제 #25
0
 def do_send(self, message, target):
     msg = Const.get_empty_message()
     msg.update(message)
     self.channel.send(msg, target)
예제 #26
0
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns

import Const

const = Const.Const()

plt.rcParams["font.size"] = 24
font = {'family': 'meiryo'}
matplotlib.rc('font', **font)

data = pd.read_csv('100_error.csv', index_col=0)


def test(s):

    s.sort()

    cdf = []
    for i in range(len(s)):
        if i == 0:
            tmp = 1.0 / len(s)
        else:
            tmp = tmp + 1.0 / len(s)
        cdf.append(tmp)
    return s, cdf

예제 #27
0
 def GetUnits(self, UP=None):
     return Const.default_unit()
예제 #28
0
 def jacobian(self, x):        
     const = Const() 
     ii = get_var_idx(self.case)
     simple_powerbalance = np.zeros_like(x)
     simple_powerbalance[ii['i1']['pg']:ii['iN']['pg']] = 1
     return simple_powerbalance
예제 #29
0
 def GetUnits(self, UP=None):
   return Const.default_unit()
예제 #30
0
def runcopf(c, flat_start):
    const = Const()
    
    nb     = c.bus.shape[0]
    ng     = c.gen.shape[0]
    nbr    = c.branch.shape[0]
    neq    = 2 * nb
    niq    = 2 * ng + nb + nbr
    neqnln = 2 * nb
    niqnln = nbr

    ii = get_var_idx(c)

    if flat_start:
        # x0 = np.concatenate((deg2rad(c.bus.take(const.VA, axis=1)), \
        #     c.bus[:,[const.VMIN, const.VMAX]].mean(axis=1), \
        #     c.gen[:,[const.PMAX, const.PMIN]].mean(axis=1) / c.mva_base, \
        #     c.gen[:,[const.QMAX, const.QMIN]].mean(axis=1) / c.mva_base), axis=0)
        x0 = np.concatenate((np.zeros(nb), \
            c.bus[:,[const.VMIN, const.VMAX]].mean(axis=1), \
            c.gen[:,[const.PMAX, const.PMIN]].mean(axis=1) / c.mva_base, \
            c.gen[:,[const.QMAX, const.QMIN]].mean(axis=1) / c.mva_base), axis=0)
    else:
        x0 = np.genfromtxt(c.path+"x0.csv", delimiter=',')
        
    xmin = np.concatenate((-np.inf * np.ones(nb), \
                           c.bus[:, const.VMIN], \
                           c.gen[:, const.PMIN] / c.mva_base, \
                           c.gen[:, const.QMIN] / c.mva_base), axis=0)
    xmax = np.concatenate((np.inf * np.ones(nb), \
                           c.bus[:, const.VMAX], \
                           c.gen[:, const.PMAX] / c.mva_base, \
                           c.gen[:, const.QMAX] / c.mva_base), axis=0)

    xmin[(c.bus[:, const.BUS_TYPE] == 3).nonzero()] = 0
    xmax[(c.bus[:, const.BUS_TYPE] == 3).nonzero()] = 0

    ####################################################################
    # Polynomial Cost Functions (f)
    #################################################################### 
    f_fcn   = lambda x: costfcn(x, c)
    df_fcn  = lambda x: costfcn_jac(x, c)
    d2f_fcn = lambda x: costfcn_hess(x, c)

    ####################################################################
    # Simple Power Balance Constraint (Linear, lossless)
    ####################################################################   
    simple_powerbalance = np.zeros_like(x0)
    tload = sum(c.bus[:,const.PD]) / c.mva_base
    simple_powerbalance[ii['i1']['pg']:ii['iN']['pg']] = 1
    simple_lincons = {'type': 'eq',
        'fun' : lambda x: sum(x[ii['i1']['pg']:ii['iN']['pg']]) - tload,
        'jac' : lambda x: simple_powerbalance}
    
    ####################################################################
    # Nonlinear Power Flow Constraints (g: eqcons, h: ineqcons)
    ####################################################################  
    eqcons   = {'type': 'eq',
                'fun' : lambda x: acpf_consfcn(x, c),
                'jac' : lambda x: acpf_consfcn_jac(x, c)}
    ineqcons = {'type': 'ineq',
                'fun' : lambda x: linerating_consfcn(x, c),
                'jac' : lambda x: linerating_consfcn_jac(x, c)}

    ####################################################################
    # Test Environment
    #################################################################### 
    all_cons = (eqcons, ineqcons)
    bnds = build_bound_cons(xmin, xmax)

    start_time = time()
    res = minimize(f_fcn, x0, jac=df_fcn, hess=d2f_fcn, bounds=bnds, \
        constraints=all_cons, options={'disp': False})
    end_time = time()

    ii = get_var_idx(c)
    res_va = rad2deg(res.x[ii['i1']['va']:ii['iN']['va']])
    res_vm = res.x[ii['i1']['vm']:ii['iN']['vm']]
    res_pg = res.x[ii['i1']['pg']:ii['iN']['pg']] * c.mva_base
    res_qg = res.x[ii['i1']['qg']:ii['iN']['qg']] * c.mva_base

    float_fmtr = {'float_kind': lambda x: "%7.3f" % x}

    print('___________')  
    print('     Statue | Exit mode %d' % res.status)
    print('    Message | %s' % res.message)
    print('       Iter | %d' % res.nit)
    print('   Time (s) | %.8f' % (end_time - start_time))
    print('  Objective | %.3f $/hr' % res.fun)
    print('  VA (deg)  | %s' % np.array2string(res_va[0:7], formatter=float_fmtr))
    print('  VM (pu)   | %s' % np.array2string(res_vm[0:7], formatter=float_fmtr))
    print('  PG (MW)   | %s' % np.array2string(res_pg, formatter=float_fmtr))
    print('  QG (MVAR) | %s' % np.array2string(res_qg, formatter=float_fmtr))
    print('___________ | ')  

    return {'VA': res_va.tolist(), 'VM': res_vm.tolist(), 'PG': res_pg.tolist(), 'QG': res_qg.tolist()}
예제 #31
0
 def __init__(self, rawquery):
     self.rawquery = rawquery
     sanquery = Const.sanitize(rawquery).split()
     self.query = queryfix(sanquery)
     self.reorderedterms = []
예제 #32
0
        ])

    def get_A(self):
        # Known inlet and outlet fluids to calculate the aperture area
        self.st_o.fluid = self.st_i.fluid
        self.st_o.flow_rate = self.st_i.flow_rate
        # Assume no pressure loss
        self.st_o.pressure = self.st_i.pressure
        self.st_o.pressure = self.st_i.pressure
        guess = np.array([500, 300, 19])
        # options = optimset('Display','iter')
        x = fsolve(self.CalcDishCollector3, guess)
        self.A = x[2]


if __name__ == '__main__':
    dc = DishCollector()
    st_i = Stream()
    st_i.fluid = Const.FLUID[2]
    st_i.temperature = Const.convert_temperature(150, 'C', 'K')
    st_i.pressure = 4e5
    st_i.flow_rate[0] = 0.07
    dc.st_i = st_i
    st_o = Stream()
    st_o.fluid = Const.FLUID[2]
    # st_o.temperature = Const.convert_temperature(239.26, 'C', 'K')
    st_o.pressure = 4e5
    dc.st_o = st_o
    dc.amb.irradiance = 700
    dc.get_T_o()