예제 #1
0
def Tdfind(wv, p):
    """
    Tdfind(wv, p)

    Calculates the due point temperature of an air parcel.

    Parameters
    - - - - - -
    wv : float
        Mixing ratio (kg/kg).
    p : float
        Pressure (Pa).

    Returns
    - - - -
    Td : float
        Dew point temperature (K).

    Examples
    - - - - -
    >>> Tdfind(0.001, 8.e4)
    253.39429263963504

    References
    - - - - - -
    Emanuel 4.4.14 p. 117
    
    """
    c = constants();    
    e = wv * p / (c.eps + wv);
    denom = (17.67 / np.log(e / 611.2)) - 1.;
    Td = 243.5 / denom;
    Td = Td + 273.15;
    return Td
예제 #2
0
def calcTvDiff(press, thetae0, interpTenv, interpTdEnv):
    """
    
    Calculates the virtual temperature difference between the thetae0
    moist adiabat and a given sounding at some pressure.
    
    Parameters
    - - - - - -
    
    press: pressure (Pa)
    thetae0: equivalent potential temperature of the adiabat (K)
    interpTenv: interpolator for environmental temperature (deg C)
    interpTdEnv: interpolator for environmental dew point temperature (deg C)
    
    Returns
    - - - - - -
    TvDiff: the virtual temperature difference at pressure press 
    between the thetae0 moist adiabat and the given sounding (K).
    
   
    """
    
    c = constants()
    Tcloud=findTmoist(thetae0,press)
    wvcloud=wsat(Tcloud,press)
    Tvcloud=Tcloud*(1. + c.eps*wvcloud)
    Tenv=interpTenv(press*1.e-2) + c.Tc
    Tdenv=interpTdEnv(press*1.e-2) + c.Tc
    wvenv=wsat(Tdenv,press)
    Tvenv=Tenv*(1. + c.eps*wvenv)
    return Tvcloud - Tvenv
    
    
예제 #3
0
파일: L.py 프로젝트: CCheng1231/A405
def L(T):
    """
    L(T)

    Calculates the latent heat of vapourization for a given
    temperature 'T'.

    Parameters
    - - - - - -
    T : float
        Temperature (K).

    Returns
    - - - -
    theL : float
        Latent heat of vaporization (J/kg)

    Examples
    - - - - -
    >>> L(300.)
    2438708.0
    
    """
    c=constants();
    theL = c.lv0 + (c.cpv - c.cl) * (T - c.Tc);
    return theL
예제 #4
0
파일: thetaes.py 프로젝트: CCheng1231/A405
def thetaes(T, p):
    """
    thetaes(T, p)

    Calculates the pseudo equivalent potential temperature of an air
    parcel.

    Parameters
    - - - - - -
    T : float
        Temperature (K).
    p : float
        Pressure (Pa).


    Returns
    - - - -
    thetaep : float
        Pseudo equivalent potential temperature (K).


    Notes
    - - -
    It should be noted that the pseudo equivalent potential
    temperature (thetaep) of an air parcel is not a conserved
    variable.


    References
    - - - - - -
    Emanuel 4.7.9 p. 132


    Examples
    - - - - -
    >>> thetaes(300., 8.e4)
    412.97362667593831
    
    """
    c = constants();
    # The parcel is saturated - prohibit supersaturation with Td > T.
    Tlcl = T;
    wv = wsat(T, p);
    thetaval = theta(T, p, wv);
    power = 0.2854 * (1 - 0.28 * wv);
    thetaep = thetaval * np.exp(wv * (1 + 0.81 * wv) * \
                                (3376. / Tlcl - 2.54))
    #
    # peg this at 450 so rootfinder won't blow up
    #
    if thetaep > 450.:
        thetaep = 450;

    return thetaep
예제 #5
0
def thetaes(T, p):
    """
    thetaes(T, p)

    Calculates the pseudo equivalent potential temperature of an air
    parcel.

    Parameters
    - - - - - -
    T : float
        Temperature (K).
    p : float
        Pressure (Pa).


    Returns
    - - - -
    thetaep : float
        Pseudo equivalent potential temperature (K).


    Notes
    - - -
    It should be noted that the pseudo equivalent potential
    temperature (thetaep) of an air parcel is not a conserved
    variable.


    References
    - - - - - -
    Emanuel 4.7.9 p. 132


    Examples
    - - - - -
    >>> thetaes(300., 8.e4)
    412.97362667593831
    
    """
    c = constants()
    # The parcel is saturated - prohibit supersaturation with Td > T.
    Tlcl = T
    wv = wsat(T, p)
    thetaval = theta(T, p, wv)
    power = 0.2854 * (1 - 0.28 * wv)
    thetaep = thetaval * np.exp(wv * (1 + 0.81 * wv) * \
                                (3376. / Tlcl - 2.54))\

    #if thetaep > 550:
    #    thetaep = 550

    return thetaep
예제 #6
0
파일: model.py 프로젝트: pf4d/issm
    def __init__(self):  #{{{

        # classtype=model.properties

        # for classe in dict.keys(classtype):
        # 	print classe
        # 	self.__dict__[classe] = classtype[str(classe)]

        self.mesh = mesh2d()
        self.mask = mask()
        self.geometry = geometry()
        self.constants = constants()
        self.smb = SMBforcing()
        self.basalforcings = basalforcings()
        self.materials = matice()
        self.damage = damage()
        self.friction = friction()
        self.flowequation = flowequation()
        self.timestepping = timestepping()
        self.initialization = initialization()
        self.rifts = rifts()
        self.slr = slr()

        self.debug = debug()
        self.verbose = verbose()
        self.settings = settings()
        self.toolkits = toolkits()
        self.cluster = generic()

        self.balancethickness = balancethickness()
        self.stressbalance = stressbalance()
        self.groundingline = groundingline()
        self.hydrology = hydrologyshreve()
        self.masstransport = masstransport()
        self.thermal = thermal()
        self.steadystate = steadystate()
        self.transient = transient()
        self.levelset = levelset()
        self.calving = calving()
        self.gia = giaivins()

        self.autodiff = autodiff()
        self.inversion = inversion()
        self.qmu = qmu()
        self.amr = amr()

        self.results = results()
        self.outputdefinition = outputdefinition()
        self.radaroverlay = radaroverlay()
        self.miscellaneous = miscellaneous()
        self.private = private()
    def run(self):
        self.connected = True
        print "Connection %d started" % self.connection_id
        constant = constants()
        try:
            recv_data = self.client.recv(self.buffer_size)
            try:
                recv_packet = packet(recv_data)
            except packet_exception as e:
                self.master.debug("[%d] Invalid Packet, closing connection" % self.connection_id)
                self.connected = False
            print "packet type is ",recv_packet.packet_type
            if recv_packet.packet_type == constant.JOIN:
                doc = recv_packet.doc_name
                print doc, "this is the doc... 1"
                print doc_index;
                if doc in doc_index.keys():
                    send_packet  = packet()
                    send_packet.packet_type = constant.Dummy
                    send_packet.list_of_ip = doc_index[doc]
                    self.__send(send_packet)
                    doc_index[doc].append([recv_packet.my_host_name,recv_packet.my_port_name]);
                else:
                    doc = recv_packet.doc_name
                    print doc, "this is the doc... 2"
                    print doc_index;
                    print "i am in else...",recv_packet.my_host_name,recv_packet.my_port_name
                    print "doc_index",doc_index
                    doc_index[doc] = list([[recv_packet.my_host_name,recv_packet.my_port_name]]);
                    print "doc_index",doc_index
                    send_packet  = packet()
                    send_packet.packet_type  = constant.NewFile
                    self.__send(send_packet)

                print "client want to join " + doc

        except socket.timeout:
            #timeout hit
            print "[%d] Client timed out, terminating thread" % self.connection_id
            self.connected = False

        except socket.error as e:
            self.master.debug("socket.error (%d, %s)" % (e.errno, e.strerror))
            if e.errno == 10054:
                print "Connection closed by the client..."
                self.connected = False

        #little nap for the cpu
        time.sleep(0.3)

        self.terminate()
예제 #8
0
 def __init__(self,text_data=None):
     self.packet_id = -1
     self.packet_type = constants().Dummy
     self.stamp = 0
     self.my_host_name = None
     self.my_port_name = None
     self.data = None
     self.fields = {}
     self.list_of_ip = []
     if text_data is not None:
         self.__from_string(text_data)
     else:
         self.packet_id = get_packet_id()
         self.packet_type = self.Ping
         self.fields = {}
예제 #9
0
def thetal(T, p, wv, wl):
    """
    thetal(T,p,wv,wl)

    Calculates the liquid water potential temperature of a parcel.

    Parameters
    - - - - - -
    T : float
        Temperature (K).
    p : float
        Pressure (Pa)
    wv : float
        Vapour mixing ratio (kg/kg).
    wl : float
        Liquid water potential temperature (kg/kg).


    Returns
    - - - -
    thetalOut : float
        Liquid water potential temperature (K).


    References
    - - - - - -
    Emanuel 4.5.15 p. 121

    Examples
    - - - - -
    >>> thetal(300., 8.e4, 0.03, 0.01)
    298.21374486200278
    
    """
    c = constants()
    Lval = L(T)
    wt = wv + wl
    chi = (c.Rd + wt * c.Rv) / (c.cpd + wt * c.cpv)
    gamma = wt * c.Rv / (c.cpd + wt * c.cpv)
    thetaVal = T * (c.p0 / p)**chi
    term1 = (1 - wl / (1. + wt)) * (1 - wl / (c.eps + wt))**(chi - 1)
    term2 = (1 - wl / wt)**(-1. * gamma)
    cp = c.cpd + wt * c.cpv
    thetalOut = thetaVal * term1 * term2 \
                * np.exp(-1. * Lval * wl/(cp*T))

    return thetalOut
예제 #10
0
파일: thetal.py 프로젝트: CCheng1231/A405
def thetal(T,p,wv,wl):
    """
    thetal(T,p,wv,wl)

    Calculates the liquid water potential temperature of a parcel.

    Parameters
    - - - - - -
    T : float
        Temperature (K).
    p : float
        Pressure (Pa)
    wv : float
        Vapour mixing ratio (kg/kg).
    wl : float
        Liquid water potential temperature (kg/kg).


    Returns
    - - - -
    thetalOut : float
        Liquid water potential temperature (K).


    References
    - - - - - -
    Emanuel 4.5.15 p. 121

    Examples
    - - - - -
    >>> thetal(300., 8.e4, 0.03, 0.01)
    298.21374486200278
    
    """
    c = constants();
    Lval = L(T);
    wt = wv + wl;
    chi = (c.Rd + wt * c.Rv) / (c.cpd + wt * c.cpv);
    gamma = wt * c.Rv / (c.cpd + wt * c.cpv);
    thetaVal = T * (c.p0 / p) ** chi;
    term1 = (1 - wl / (1. + wt)) * (1 - wl / (c.eps + wt)) ** (chi-1)
    term2 = (1 - wl / wt) ** (-1. * gamma);
    cp = c.cpd + wt * c.cpv;
    thetalOut = thetaVal * term1 * term2 \
                * np.exp(-1. * Lval * wl/(cp*T));

    return thetalOut
    def __init__(self, src='multi_plant', labels='multi_label'):
        self.c = constants()
        self.window1 = self.c.window.window1
        self.window2 = self.c.window.window2

        cv.namedWindow(self.window1)
        cv.namedWindow(self.window2)

        cv.moveWindow(self.window2, 550, 90)

        cv.createTrackbar(self.c.HSV.low_H_name, self.window1,
                          self.c.HSV.low_H, self.c.HSV.max_value_H,
                          self.on_low_H_thresh_trackbar)
        cv.createTrackbar(self.c.HSV.high_H_name, self.window1,
                          self.c.HSV.high_H, self.c.HSV.max_value_H,
                          self.on_high_H_thresh_trackbar)
        cv.createTrackbar(self.c.HSV.low_S_name, self.window1,
                          self.c.HSV.low_S, self.c.HSV.max_value,
                          self.on_low_S_thresh_trackbar)
        cv.createTrackbar(self.c.HSV.high_S_name, self.window1,
                          self.c.HSV.high_S, self.c.HSV.max_value,
                          self.on_high_S_thresh_trackbar)
        cv.createTrackbar(self.c.HSV.low_V_name, self.window1,
                          self.c.HSV.low_V, self.c.HSV.max_value,
                          self.on_low_V_thresh_trackbar)
        cv.createTrackbar(self.c.HSV.high_V_name, self.window1,
                          self.c.HSV.high_V, self.c.HSV.max_value,
                          self.on_high_V_thresh_trackbar)

        self.plants, self.plant_groups, self.labels = self.prepare_plant_collection(
            src, labels)

        # source https://docs.opencv.org/3.4/d1/dc5/tutorial_background_subtraction.html

        for key in self.plant_groups:
            if self.c.bgsub.mod == 'MOG2':
                backSub = cv.createBackgroundSubtractorMOG2(history=60,
                                                            detectShadows=True)
            elif self.c.bgsub.mod == 'KNN':
                backSub = cv.createBackgroundSubtractorKNN()
            fgMask = None
            for i, image in enumerate(self.plant_groups[key]):
                fgMask = backSub.apply(image)
                self.plant_groups[key][i] = fgMask
예제 #12
0
 def sendOperationToAllPeers(self):
     constant = constants()
     while 1:
         if self.set_of_operation == []:
             time.sleep(1)
         else:
             
             peers = self.peers
             operation = self.set_of_operation
             self.set_of_operation = []
             print "===================SENDING OPERATIONS TO OTHER PEERS===================== "
             for op in operation:
                 for peer in peers:
                     print "sending to peer", peer
                     self.connect_peer(peer[0],peer[1])
                     send_packet = packet()
                     send_packet.packet_type = constant.OperationTransformation
                     send_packet.data = "(" + str(op[0]) + "," + str(op[1]) + "," + str(op[2]) + ")"
                     self.__send(send_packet)
예제 #13
0
def calcConc(m, V, MM=368):
    """
    Calculate the molar concentration of a sample with mass m dissolved in
    volume V
    ==========  ===============================================================
    Input       Meaning
    ----------  ---------------------------------------------------------------
    m           Mass of the solute [g]
    V           Volume of the solution [L]
    MM          Molar mass of the solute [g/mole]
                Default set to 368 g/mole for Oregon Green
    ==========  ===============================================================

    ==========  ===============================================================
    Output      Meaning
    ----------  ---------------------------------------------------------------
    c           Concentration of the solution [mol/L]
    ==========  ===============================================================

    """

    Avogadro = constants('avogadro')
    
    # grams to moles of solute
    moles = m / MM
    
    # concentration [mole/L]
    c = moles / V
    
    # concentration [particles/L]
    c2 = c * Avogadro
    
    # concentration [particles/fL]
    c3 = c2 / 1e15
    
    # print results
    print('Concentration: {:.2e}'.format(c) + ' M = {:.2e}'.format(c2) + ' particles/L = {:.2e}'.format(c3) + ' particles/fL')
    
    return c
예제 #14
0
def StokesEinstein(D, T=293, visc=1e-3):
    """
    Calculate the diameter of particles based on the Stokes-Einstein equation
    ==========  ===============================================================
    Input       Meaning
    ----------  ---------------------------------------------------------------
    D           Diffusion coefficient of the particles [in µm^2/s]
    T           Temperature of the suspension [in K]
    visc        Viscosity of the solvent [in Pa.s]
    ==========  ===============================================================

    ==========  ===============================================================
    Output      Meaning
    ----------  ---------------------------------------------------------------
    d           Diameter of the particles [in m]
    ==========  ===============================================================

    """

    kb = constants('boltzmann')
    r = kb * T / 6 / np.pi / visc / D
    d = 2 * r
    return d
예제 #15
0
def theta(*args):
    """
    theta(*args)

    Computes potential temperature.
    Allows for either T,p or T,p,wv as inputs.
    

    Parameters
    - - - - - -
    T : float
        Temperature (K).
    p : float
        Pressure (Pa).


    Returns
    - - - -
    thetaOut : float
        Potential temperature (K).


    Other Parameters
    - - - - - - - - -
    wv : float, optional
        Vapour mixing ratio (kg,kg). Can be appended as an argument
        in order to increase precision of returned 'theta' value.
    
    
    Raises
    - - - -
    NameError
        If an incorrect number of arguments is provided.
    
    
    References
    - - - - - -
    Emanuel p. 111 4.2.11


    Examples
    - - - - -
    >>> theta(300., 8.e4) # Only 'T' and 'p' are input.
    319.72798180767984
    >>> theta(300., 8.e4, 0.001) # 'T', 'p', and 'wv' all input.
    319.72309475657323
    
    """
    c = constants()
    if len(args) == 2:
        wv = 0
    elif len(args) == 3:
        wv = args[2]
    else:
        raise NameError('need either T,p or T,p,wv')

    T = args[0]
    p = args[1]
    power = c.Rd / c.cpd * (1. - 0.24 * wv)
    thetaOut = T * (c.p0 / p)**power
    return thetaOut
예제 #16
0
def wsat(Temp, press):
    """
    wsat(Temp, press)

    Calculates the saturation vapor mixing ratio of an air parcel.

    Parameters
    - - - - - -
    Temp : float or array_like
        Temperature in Kelvin.
    press : float or array_like
        Pressure in Pa.

    Returns
    - - - -
    theWs : float or array_like 
        Saturation water vapor mixing ratio in (kg/kg).

    Raises
    - - - -
    IOError
        If both 'Temp' and 'press' are array_like.

    Examples
    - - - - -
    >>> wsat(300, 8e4)
    0.028751159650442507
    >>> wsat([300,310], 8e4)
    [0.028751159650442507, 0.052579529573838296]
    >>> wsat(300, [8e4, 7e4])
    [0.028751159650442507, 0.033076887758679716]
    >>> wsat([300, 310], [8e4, 7e4])
    Traceback (most recent call last):
        ...
    IOError: Can't have two vector inputs.

    """
    c = constants()
    es = esat(Temp)

    # We need to test for all possible cases of (Temp,press)
    # combinations (ie. (vector,vector), (vector,scalar),
    # (scalar,vector), or (scalar,scalar).

    try:
        len(es)
    except:
        esIsVect = False
    else:
        esIsVect = True

    try:
        len(press)
    except:
        pressIsVect = False
    else:
        pressIsVect = True

    if esIsVect and pressIsVect:
        raise IOError, "Can't have two vector inputs."
    elif esIsVect:
        theWs = c.eps * es / (press - es)
        #theWs = [(c.eps * i/ (press - i)) for i in es]
        # Limit ws values so rootfinder doesn't blow up.
        #theWs = list(replaceelem(theWs,0,0.060))
    elif pressIsVect:
        theWs = c.eps * es / (press - es)
        #theWs = [(c.eps * es/ (i - es)) for i in press]
        # Limit ws values so rootfinder doesn't blow up.
        #theWs = list(replaceelem(theWs,0,0.060))
    else:  # Neither 'es' nor 'press' in a vector.
        theWs = (c.eps * es / (press - es))
        # Limit ws value so rootfinder doesn't blow up.
        if theWs > 0.060: theWs = 0.060
        elif theWs < 0: theWs = 0

    # Set minimum and maximum acceptable values for theWs.

    try:
        len(theWs)
    except:
        if theWs > 0.060: theWs = 0.060
        elif theWs < 0: theWs = 0
    else:
        theWs[theWs < 0] = 0
        theWs[theWs > 0.060] = 0.060
    #    theWs = list(replaceelem(theWs, 0, 0.060))

    return theWs
예제 #17
0
    def loop(self,my_host_name,my_port_name):
        constant = constants()
        print my_host_name,my_port_name
        while self.connected:
            try:
                send_packet = packet()
                send_packet.packet_type = constant.JOIN
                send_packet.my_host_name = my_host_name
                send_packet.my_port_name = my_port_name
                print "details packet_type",send_packet.packet_type
                send_packet.doc_name = self.file_name
                self.__send(send_packet)

                recv_packet = self.__receive()
                self.socket.close();

                self.bind_socket.bind((my_host_name,my_port_name))
                print "creating server at ",my_host_name,my_port_name
                self.bind_socket.listen(10)

                thread.start_new_thread(self.sendOperationToAllPeers,())
                thread.start_new_thread(self.mergeNewOperations,())

                if recv_packet.packet_type == constant.NewFile:  #new file created.
                    while 1:
                        
                        peer_socket, peer_address = self.bind_socket.accept()

                        print "connection accepted ....."
                        try:
                            recv_peer_packet = self.__peer_receive(peer_socket)
                            # <packet_type 1000: my_host_name: my_port_name> 
                            if recv_peer_packet.packet_type == constant.NewConnection:
                                handleNewConnection()
                                

                            if recv_peer_packet.packet_type == constant.OperationTransformation:
                                self.set_of_operation_to_merge.append(recv_peer_packet.data)

                            if recv_peer_packet.packet_type == constant.getData:
                                print "some peer wants my data workspace.data"
                                send_packet = packet()
                                print "my workspace data before is ", self.workspace.get_data()
                                
                                print "my workspace data is ", self.workspace.get_data()
                                send_packet.data = self.workspace.get_data()
                                self.__peer_send(peer_socket,send_packet)
                            peer_socket.close()
                        except:
                            peer_socket.close()
                            print "error 265"
                    
                else:
                    print "joining existing file list_of_ip: ",recv_packet.list_of_ip
                
                    for peer in recv_packet.list_of_ip:
                        print "perr details are: ", peer
                        self.peers.append(peer)
                        self.connect_peer(peer[0],peer[1])
                        send_packet = packet()
                        send_packet.packet_type = constant.NewConnection
                        send_packet.my_host_name = my_host_name
                        send_packet.my_port_name = my_port_name
                        self.__send(send_packet)
                        recv_peer_ack = self.__receive()
                    peer = recv_packet.list_of_ip[0]
                    self.connect_peer(peer[0],peer[1])
                    send_packet.packet_type = constant.getData
                    self.__send(send_packet)
                    recv_peer_data = self.__receive()
                    self.workspace.set_data(recv_peer_data.data)
                    print "recv_data ", recv_peer_data.data
                    self.__workspace_received()

                    print "recv_packet data:",recv_peer_data.data
                    while 1:
                    
                        print "waiting to accept....."
                        peer_socket, peer_address = self.bind_socket.accept()
                        print "connection accepted ....."
                        try:
                            recv_peer_packet = self.__peer_receive(peer_socket)
                            # <packet_type 1000: my_host_name: my_port_name> 
                            if recv_peer_packet.packet_type == constant.NewConnection:
                                handleNewConnection()

                            if recv_peer_packet.packet_type == constant.OperationTransformation:
                                self.set_of_operation_to_merge.append(recv_peer_packet.data)

                            if recv_peer_packet.packet_type == constant.getData:
                                print "some peer wants my data workspace.data"
                                send_packet = packet()
                                print "my workspace data before is ", self.workspace.get_data()
                                
                                print "my workspace data is ", self.workspace.get_data()
                                send_packet.data = self.workspace.get_data()
                                self.__peer_send(peer_socket,send_packet)
                            peer_socket.close()
                        except:
                            peer_socket.close()
                            print "error 265"
                

            except socket.error as e:
                print "Socket error [%s, %s]" % (e.errno, e.strerror)
                self.connected = False
                self.__disconnected()

            time.sleep(0.2)
예제 #18
0
def thetaep(Td, T, p):
    """
    thetaep(Td, T, p)

    Calculates the pseudo equivalent potential temperature of a
    parcel. 


    Parameters
    - - - - - -
    Td : float
        Dewpoint temperature (K).
    T : float
        Temperature (K).
    p : float
        Pressure (Pa).


    Returns
    - - - -
    thetaepOut : float
        Pseudo equivalent potential temperature (K).


    Notes
    - - -
    Note that the pseudo equivalent potential temperature of an air
    parcel is not a conserved variable.


    References
    - - - - - -
    Emanuel 4.7.9 p. 132


    Examples
    - - - - -
    >>> thetaep(280., 300., 8.e4) # Parcel is unsaturated.
    344.99830738253371
    >>> thetaep(300., 280., 8.e4) # Parcel is saturated.
    321.5302927767795
    
    """
    c = constants()
    if Td < T:
        #parcel is unsaturated
        [Tlcl, plcl] = LCLfind(Td, T, p)
        wv = wsat(Td, p)
    else:
        #parcel is saturated -- prohibit supersaturation with Td > T
        Tlcl = T
        wv = wsat(T, p)

    # $$$   disp('inside theate')
    # $$$   [Td,T,wv]
    thetaval = theta(T, p, wv)
    power = 0.2854 * (1 - 0.28 * wv)
    thetaep = thetaval * np.exp(wv * (1 + 0.81 * wv) \
                                   * (3376. / Tlcl - 2.54))
    #
    # peg this at 450 so rootfinder won't blow up
    #
    #thetaepOut = thetaep
    #if(thetaepOut > 450.):
    #    thetaepOut = 450;
    return thetaep
예제 #19
0
from threading import Thread
import time
import sys
import os
# add module folders to path
sys.path.append(os.getcwd()+'/Gmodule')
sys.path.append(os.getcwd()+'/MSHmodule')
import gExtract
import mshExtract
from MainFrame import MFrame
from constants import constants

#initializing vizulization constants for model and also variables space
cons=constants()
print('constants initialized')

## open stl file
print('exctracting geometry from file')
path='D:/tre.stl'
model,cmass=gExtract.eSTL(path) # model=[[normal,vecn1,vecn2,vecn3],... ](triangles); cmass = (x,y,z)
print('stl surface elements: ',len(model))


##assign geometry
cons.vect=model
cons.cmass_xyz=cmass
cons.Gwidgets.append('geometry')
print('model assigned to constants')

## open mesh file
print('exctracting geometry from file')
예제 #20
0
def LCLfind(Td, T, p):
    """
    LCLfind(Td, T, p)

    Finds the temperature and pressure at the lifting condensation
    level (LCL) of an air parcel.

    Parameters
    - - - - - -
    Td : float
        Dewpoint temperature (K).
    T : float
        Temperature (K).
    p : float
        Pressure (Pa)

    Returns
    - - - -
    Tlcl : float
        Temperature at the LCL (K).
    plcl : float
        Pressure at the LCL (Pa).

    Raises
    - - - -
    NameError
        If the air is saturated at a given Td and T (ie. Td >= T)
    
    Examples
    - - - - -
    >>> [Tlcl, plcl] =  LCLfind(280., 300., 8.e4)
    >>> print [Tlcl, plcl]
    [275.76250387361404, 59518.928699453245]
    >>> LCLfind(300., 280., 8.e4)
    Traceback (most recent call last):
        ...
    NameError: parcel is saturated at this pressure

    References
    - - - - - -
    Emanuel 4.6.24 p. 130 and 4.6.22 p. 129
    
    """
    c = constants()

    hit = Td >= T
    if hit is True:
        raise NameError('parcel is saturated at this pressure')

    e = esat(Td)
    ehPa = e * 0.01
    #Bolton's formula requires hPa.
    # This is is an empircal fit from for LCL temp from Bolton, 1980 MWR.
    Tlcl = (2840. / (3.5 * np.log(T) - np.log(ehPa) - 4.805)) + 55.

    r = c.eps * e / (p - e)
    #disp(sprintf('r=%0.5g',r'))
    cp = c.cpd + r * c.cpv
    logplcl = np.log(p) + cp / (c.Rd * (1 + r / c.eps)) * \
              np.log(Tlcl / T)
    plcl = np.exp(logplcl)
    #disp(sprintf('plcl=%0.5g',plcl))

    return Tlcl, plcl
예제 #21
0
def O18EVA_MEAN(tmax, TC, pCO2, pCO2cave, h, v, R18_hco_ini, R18_h2o_ini, R18v, HCOMIX, h2o_new,tt):
    
    # Sourcecode to develope the evolution of the isotopic ratio of the oxygen
    # compostion of the oxygen isotopes 16O and 18O as a function of
    # temperature TC, supersaturation (pCO2), relative humidity (h) and wind
    # velocity (v). %(08.12.2010/m)
    
    eva = evaporation.evaporation(TC, h, v)
    fracs = cmodel_frac.cmodel_frac(TC)
    TK = 273.15 + TC
    #Tau precipitation (s); t=d/a (according to Baker 98)
    alpha_p = (1.188e-011 * TC**3 - 1.29e-011 * TC**2 + 7.875e-009 * TC + 4.844e-008)
    #Tau buffering, after Dreybrodt and Scholz (2010)
    T = 125715.87302 - 16243.30688*TC + 1005.61111*TC**2 - 32.71852*TC**3 + 0.43333*TC**4
    
    #Concentrations and mol mass
    outputcave = constants.constants(TC, pCO2cave)      #Concentrations of the spezies in the solution, with respect to cave pCO2                            
    HCOCAVE = outputcave[2][2]/math.sqrt(0.8)  #HCO3- concentration, with respect to cave pCO2 (mol/l)

    h2o_ini = h2o_new                          #Mol mass of the water, with respect to the volume of a single box (mol)
    H20_ini = h2o_ini*18/1000
    hco_ini = HCOMIX*H20_ini                   #Mol mass of the HCO3-(soil), with respect to the volume of a single box (mol)
    hco_eq = HCOCAVE*H20_ini                   #Mol mass of the HCO3-(cave), with respect to the volume of a single box (mol)

    #Fractionation facors for oxygen isotope
    eps_m = fracs['a18_m'] - 1                                                 
    avl = ((-7356/TK + 15.38)/1000 + 1)
    abl = 1/(fracs['e18_hco_h2o'] + 1)
    a = 1/1.008*1.003
    f = 1/6

    #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    #Calculation of the 18R

    r_hco18 = [R18_hco_ini]
    r_h2o18 = [R18_h2o_ini]
    
    if tmax > math.floor(h2o_ini/eva):
        tmax = int(math.floor(h2o_ini/eva))
        print 'DRIPINTERVALL IS TOO LONG, THE WATERLAYER EVAPORATES COMPLETLY FOR THE GIVEN d, run # %i' %(tt)
    
    dt = 1
    t=range(1,tmax+1)
            
    HCO = [HCOMIX]                                  #Konzentration von HCO3-
    hco = [hco_ini]                                 #Menge an HCO3-
    H2O = [H20_ini]
    h2o = [h2o_new]
    delta_1 = [H2O[-1]/1000/0.001]

    #"Restwassermenge" und daher konstant
    
    
    for i in t:
    
        delta_1.append(H2O[-1]/1000/0.001)
        delta = (H2O[-1]/1000)/0.001
        
        #Neue Wassermenge
        h2o.append(h2o[-1] - eva*dt)              #Water (mol)
        d_h2o = -eva                              #Evaporationrate (mol/l)
        H2O.append(h2o[-1]*18*1e-3)               #Water (l)
        
        HCO_EQ = HCOCAVE                       #Equilibriumconcentration
                
        #Verdundstung
        HCO_temp = (HCO[-1] - HCO_EQ) * math.exp(-dt/(delta/alpha_p)) + HCO_EQ          #HCO3- concentration after timeintervall dt
        hco.append(HCO_temp * H2O[-2])                                         #HCO3- mass (mol)
                
        HCO.append(HCO_temp * (H2O[-2]/H2O[-1]))      #HCO3- concentration after timeintervall dt and the evaporation of water
                
        r_hco18.append(r_hco18[-1] + ((eps_m*(hco[-1]-hco[-2])/hco[-1]-1/T) * r_hco18[-1] + abl/T*r_h2o18[-1]) * dt)
        r_h2o18.append(r_h2o18[-1] + ((hco[-1]/h2o[-1]/T - f/abl/h2o[-1]*(hco[-1]-hco[-2]) * r_hco18[-1] + (d_h2o/h2o[-1]*(a*avl/(1-h)-1) - hco[-1]/h2o[-1]*abl/T) * r_h2o18[-1] - a*h/(1-h)*R18v/h2o[-1]*d_h2o)) * dt)
        
    if tmax > math.floor(h2o_ini/eva):
        r_hco18 = NaN
        r_h2o18 = NaN
        hco = NaN
        h2o = NaN
        delta_1 = NaN
        
    return [r_hco18, r_h2o18, hco, h2o, delta_1]
예제 #22
0
파일: LCLfind.py 프로젝트: CCheng1231/A405
def LCLfind(Td, T, p):
    """
    LCLfind(Td, T, p)

    Finds the temperature and pressure at the lifting condensation
    level (LCL) of an air parcel.

    Parameters
    - - - - - -
    Td : float
        Dewpoint temperature (K).
    T : float
        Temperature (K).
    p : float
        Pressure (Pa)

    Returns
    - - - -
    Tlcl : float
        Temperature at the LCL (K).
    plcl : float
        Pressure at the LCL (Pa).

    Raises
    - - - -
    NameError
        If the air is saturated at a given Td and T (ie. Td >= T)
    
    Examples
    - - - - -
    >>> [Tlcl, plcl] =  LCLfind(280., 300., 8.e4)
    >>> print [Tlcl, plcl]
    [275.76250387361404, 59518.928699453245]
    >>> LCLfind(300., 280., 8.e4)
    Traceback (most recent call last):
        ...
    NameError: parcel is saturated at this pressure

    References
    - - - - - -
    Emanuel 4.6.24 p. 130 and 4.6.22 p. 129
    
    """
    c = constants();

    hit = Td >= T;
    if hit is True:
        raise NameError('parcel is saturated at this pressure');

    e = esat(Td);
    ehPa = e * 0.01; #Bolton's formula requires hPa.
    # This is is an empircal fit from for LCL temp from Bolton, 1980 MWR.
    Tlcl = (2840. / (3.5 * np.log(T) - np.log(ehPa) - 4.805)) + 55.;

    r = c.eps * e / (p - e);
    #disp(sprintf('r=%0.5g',r'))
    cp = c.cpd + r * c.cpv;
    logplcl = np.log(p) + cp / (c.Rd * (1 + r / c.eps)) * \
              np.log(Tlcl / T);
    plcl = np.exp(logplcl);
    #disp(sprintf('plcl=%0.5g',plcl))

    return Tlcl, plcl
예제 #23
0
import warpGen as wg



#constants scripts
#these create libraries where integer constants are made
#based on the file names

#story struct pre-processing
d.dialog("story_merge", "jass", ["msg"])

#quest description adding
qm.questMsg("quests_merge", "quest_struct", ["msg"])

#creates library for monster constants--however, must be integer to rawcode!
cns.constants("monsters", "tables/monsters_constants.j", "lua", ["header", "insert"], "M")

#creates library for npc names--for enumeration, string to string
#cns.constantsStr("npcs", "tables/npc_names_constants.j", "lua", ["header", "insert"])

#creates library for warp constants--integer to integer
#cns.constants("warps", "tables/warps_constants.j", "lua", ["header", "insert"])
#cns.constants("warps", "tables/warp_id_constants.j", "lua", ["header", "insert"], "w", "_ID", "Ids")

#creates library for quest constants--integer to integer
cns.constants("quests_merge", "tables/quests_constants.j", "quest_struct", ["header", "insert", "msg"])

#creates library for reward constants--integer to integer
cns.constants("reward_merge", "tables/reward_constants.j", "reward_struct", ["header", "insert"], "", "_REWARD")

#creates library for story constants--integer to integer
예제 #24
0
    def constants(self, constants_arr, jd=0.0):
        """
        Syntax: constants(constants_arr, [jd= ])
        Purpose: Parse aircraft constants XML files and return desired aircraft
                 constants in a dictionary.
        Input: 'constants_arr' - an array of desired constants as strings
               'jd' - optional argument sets Julian Date for time-dependent constants
        Output: a dictionary containing the desired constants that are correct for
                the given Julian Date.
        Notes: If no Julian Date is given, the class attribute 'jul_date' is used.
        """
        # Import the constants method.
        from constants import constants

        # Parse the default constants XML file for the desired constants.
        constants_dict = constants(constants_arr)

        # Get calibration data based on the ADPAA class attribute 'SNAME'.
        if 'Convair 580 (C-FNRC)' in self.SNAME:

            # Create a dictionary 'N_consts' with the desired constants from the
            # N555DS XML constants file using the Julian Date passed into
            # the method.
            if jd > 0.0:
                N_consts = constants(constants_arr, \
                                     fname='C-FNRC_constants.xml', jul_date=jd)

            # Create a dictionary 'N_consts' with the desired constants from the
            # N555DS XML constants file using the Julian Date calculated from
            # the filename.
            elif self.jul_date > 0.0:
                N_consts = constants(constants_arr,                \
                                     fname='C-FNRC_constants.xml', \
                                     jul_date=self.jul_date)

            else:
                print("WARNING (adpaa.py): Julian Date not set--returning only desired"+\
                      " default constants. Use the 'jd' argument to manually"+\
                      " set the Julain Date.")
                return constants_dict

            # Update the 'constant_dict' dictionary with the desired constants
            # only if a value exists for that item in the 'N_const' dictionary
            # as to not override the values already in 'const_dict'.
            for key,val in N_consts.items():
                if val != None:
                    constants_dict.update({key:val})

        if 'UND Citation II' in self.SNAME:

            # Create a dictionary 'N_consts' with the desired constants from the
            # N555DS XML constants file using the Julian Date passed into
            # the method.
            if jd > 0.0:
                N_consts = constants(constants_arr, \
                                     fname='N555DS_constants.xml', jul_date=jd)

            # Create a dictionary 'N_consts' with the desired constants from the
            # N555DS XML constants file using the Julian Date calculated from
            # the filename.
            elif self.jul_date > 0.0:
                N_consts = constants(constants_arr,                \
                                     fname='N555DS_constants.xml', \
                                     jul_date=self.jul_date)

            else:
                print("WARNING (adpaa.py): Julian Date not set--returning only desired"+\
                      " default constants. Use the 'jd' argument to manually"+\
                      " set the Julain Date.")
                return constants_dict

            # Update the 'constant_dict' dictionary with the desired constants
            # only if a value exists for that item in the 'N_const' dictionary
            # as to not override the values already in 'const_dict'.
            for key,val in N_consts.items():
                if val != None:
                    constants_dict.update({key:val})

        else:
            print("WARNING (adpaa.py): invalid ADPAA class attribute 'SNAME'--only "+\
                  "desired default constants will be returned.")

        # Remove constants that have not been found in any constants file.
        for k in constants_dict.keys():
            if constants_dict[k] == None:
                print("WARNING (adpaa.py): constant '"+k+"' does not exist and will not"+\
                      " be returned.")
                del constants_dict[k]

        return constants_dict
예제 #25
0
파일: convecSkew.py 프로젝트: sasaxuan/A405
def convecSkew(figNum):
      """       
      Usage:  convecSkew(figNum)
      Input:  figNum = integer
       Takes any integer, creates figure(figNum), and plots a
       skewT logp thermodiagram.
      Output: skew=30.
      """
      c = constants();
      plt.figure(figNum);
      plt.clf();
      yplot = range(1000,190,-10)
      xplot = range(-300,-139)
      pvals = np.size(yplot)
      tvals = np.size(xplot)
      temp = np.zeros([pvals, tvals]);
      theTheta = np.zeros([pvals, tvals]);
      ws = np.zeros([pvals, tvals]);
      theThetae = np.zeros([pvals, tvals]);      
      skew = 30; #skewness factor (deg C)

      # lay down a reference grid that labels xplot,yplot points 
      # in the new (skewT-lnP) coordinate system .
      # Each value of the temp matrix holds the actual (data)
      # temperature label (in deg C)  of the xplot, yplot coordinate.
      # pairs. The transformation is given by W&H 3.56, p. 78.  Note
      # that there is a sign difference, because rather than
      # taking y= -log(P) like W&H, I take y= +log(P) and
      # then reverse the y axis         
      
      for i in yplot:
            for j in xplot:
                  # Note that we don't have to transform the y
                  # coordinate, as it is still pressure.
                  iInd = yplot.index(i)
                  jInd = xplot.index(j)
                  temp[iInd, jInd] = convertSkewToTemp(j, i, skew);
                  Tk = c.Tc + temp[iInd, jInd];
                  pressPa = i * 100.;
                  theTheta[iInd, jInd] = theta(Tk, pressPa);
                  ws[iInd, jInd] = wsat(Tk, pressPa);
                  theThetae[iInd, jInd] = thetaes(Tk, pressPa);
                  
      #
      # Contour the temperature matrix.
      #

      # First, make sure that all plotted lines are solid.
      mpl.rcParams['contour.negative_linestyle'] = 'solid'
      tempLabels = range(-40, 50, 10);
      output1 = plt.contour(xplot, yplot, temp, tempLabels, \
                            colors='k')
      
      #
      # Customize the plot
      #
      
      plt.setp(plt.gca(), yscale='log')
      locs = np.array(range(100, 1100, 100))
      labels = locs
      plt.yticks(locs, labels) # Conventionally labels semilog graph.
      plt.setp(plt.gca(), ybound=(200, 1000))
      plt.setp(plt.getp(plt.gca(), 'xticklabels'), fontweight='bold')
      plt.setp(plt.getp(plt.gca(),'yticklabels'), fontweight='bold')
      plt.grid(True)
      plt.setp(plt.gca().get_xgridlines(), visible=False)
      plt.hold(True);
      
      thetaLabels = range(200, 380, 10);
      output2 = plt.contour(xplot, yplot, theTheta, thetaLabels, \
                        colors='b');

      wsLabels = range(6, 24, 2);
      output3 = plt.contour(xplot, yplot, (ws * 1.e3), wsLabels, \
                        colors='g');

      thetaeLabels = range(250, 380, 10);
      output4 = plt.contour(xplot, yplot, theThetae, thetaeLabels, \
                        colors='r'); 
      
      # Transform the temperature,dewpoint from data coords to
      # plotting coords.
      plt.title('skew T - lnp chart');
      plt.ylabel('pressure (hPa)');
      plt.xlabel('temperature (deg C)');

      #
      # Crop image to a more usable size
      #    
      
      TempTickLabels = range(5, 35, 5);
      TempTickCoords = TempTickLabels;
      skewTickCoords = convertTempToSkew(TempTickCoords, 1.e3, skew);
      plt.xticks(skewTickCoords, TempTickLabels)
      skewLimits = convertTempToSkew([5, 30], 1.e3, skew);
      plt.axis([skewLimits[0], skewLimits[1], 600, 1.e3]);
      
      #
      # Create line labels
      #

      fntsz = 9 # Handle for 'fontsize' of the line label.
      ovrlp = 1 # Handle for 'inline'. Any integer other than 0
                # creates a white space around the label.
                
      plt.clabel(output1, inline=ovrlp, fmt='%1d', fontsize=fntsz);
      plt.clabel(output2, inline=ovrlp, fmt='%1d', fontsize=fntsz);
      plt.clabel(output3, inline=ovrlp, fmt='%1d', fontsize=fntsz);
      plt.clabel(output4, inline=ovrlp, fmt='%1d', fontsize=fntsz);

      #
      # Flip the y axis
      #
      
      plt.setp(plt.gca(), ylim=plt.gca().get_ylim()[::-1])
      
      return skew
예제 #26
0
def O18EVA(tmax, TC, pCO2, pCO2cave, h, v, R18_hco_ini, R18_h2o_ini, R18v,
           HCOMIX, h2o_new, tt):

    # Sourcecode to develope the evolution of the isotopic ratio of the oxygen
    # compostion of the oxygen isotopes 16O and 18O as a function of
    # temperature TC, supersaturation (pCO2), relative humidity (h) and wind
    # velocity (v). %(08.12.2010/m)

    eva = evaporation.evaporation(TC, h, v)
    fracs = cmodel_frac.cmodel_frac(TC)
    TK = 273.15 + TC
    #Tau precipitation (s); t=d/a (according to Baker 98)
    alpha_p = (1.188e-011 * TC**3 - 1.29e-011 * TC**2 + 7.875e-009 * TC +
               4.844e-008)
    #Tau buffering, after Dreybrodt and Scholz (2010)
    T = 125715.87302 - 16243.30688 * TC + 1005.61111 * TC**2 - 32.71852 * TC**3 + 0.43333 * TC**4

    #Concentrations and mol mass
    outputcave = constants.constants(
        TC, pCO2cave
    )  #Concentrations of the spezies in the solution, with respect to cave pCO2
    HCOCAVE = outputcave[2][2] / math.sqrt(
        0.8)  #HCO3- concentration, with respect to cave pCO2 (mol/l)

    h2o_ini = h2o_new  #Mol mass of the water, with respect to the volume of a single box (mol)
    H20_ini = h2o_ini * 18 / 1000.
    hco_ini = HCOMIX * H20_ini  #Mol mass of the HCO3-(soil), with respect to the volume of a single box (mol)
    #hco_eq = HCOCAVE*H20_ini                   #Mol mass of the HCO3-(cave), with respect to the volume of a single box (mol)

    #Fractionation facors for oxygen isotope
    eps_m = fracs['a18_m'] - 1
    avl = ((-7356. / TK + 15.38) / 1000. + 1)
    abl = 1 / (fracs['e18_hco_h2o'] + 1)
    a = 1 / 1.008 * 1.003
    f = 1 / 6

    #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    #Calculation of the 18R

    r_hco18 = [R18_hco_ini]
    r_h2o18 = [R18_h2o_ini]

    if tmax > math.floor(h2o_ini / eva):
        tmax = int(math.floor(h2o_ini / eva))
        print 'DRIPINTERVALL IS TOO LONG, THE WATERLAYER EVAPORATES COMPLETLY FOR THE GIVEN d, run # %i' % (
            tt)

    dt = 1
    t = range(1, tmax + 1)

    HCO = [HCOMIX]  #Konzentration von HCO3-
    hco = [hco_ini]  #Menge an HCO3-
    H2O = [H20_ini]
    h2o = [h2o_new]

    #"Restwassermenge" und daher konstant

    HCO_EQ = HCOCAVE  #Equilibriumconcentration

    for i in t:

        delta = (H2O[-1] / 1000.) / 0.001

        #Neue Wassermenge
        h2o.append(h2o[-1] - eva * dt)  #Water (mol)
        d_h2o = -eva  #Evaporationrate (mol/l)
        H2O.append(h2o[-1] * 18 * 1e-3)  #Water (l)

        #Verdundstung
        HCO_temp = (HCO[-1] - HCO_EQ) * math.exp(
            -dt /
            (delta /
             alpha_p)) + HCO_EQ  #HCO3- concentration after timeintervall dt
        hco.append(HCO_temp * H2O[-2])  #HCO3- mass (mol)

        HCO.append(
            HCO_temp * (H2O[-2] / H2O[-1])
        )  #HCO3- concentration after timeintervall dt and the evaporation of water

        r_hco18.append(r_hco18[-1] +
                       ((eps_m *
                         (hco[-1] - hco[-2]) / hco[-1] - 1 / T) * r_hco18[-1] +
                        abl / T * r_h2o18[-1]) * dt)
        r_h2o18.append(r_h2o18[-1] + (
            (hco[-1] / h2o[-1] / T - f / abl / h2o[-1] *
             (hco[-1] - hco[-2]) * r_hco18[-1] +
             (d_h2o / h2o[-1] *
              (a * avl /
               (1 - h) - 1) - hco[-1] / h2o[-1] * abl / T) * r_h2o18[-1] -
             a * h / (1 - h) * R18v / h2o[-1] * d_h2o) * dt))

    return [r_hco18[-1], r_h2o18[-1], HCO[-1], hco[-1], H2O[-1], h2o[-1]]
예제 #27
0
import datetime as dt
import os

import constants
c = constants.constants()

import globals
g = globals.ioGlobals()

# Logging system for ioController and testController


class log():
    # Very simple logging system.  Just formats the supplied message with a timestamp
    # and a level (which defaults to "debug").  Outputs the message to a TCP data client
    # if it's connected

    def __init__(self):
        # Open a file on the local drive to which we're going to send all the logging
        # messages.  Note that errors here are printed (rather than logged) because
        # the log file is not set up until we exit so printing is the least-worst
        # thing to do

        # First we need to create a log directory if there's not one already
        try:
            os.mkdir(c.logDirectory)
            print('Created log directory: ' + c.logDirectory)

        except FileExistsError:
            # We got an error because the logs directory already exists.  Now we need
            # to delete all the old log files.  Work out the cut off for deleting them
예제 #28
0
파일: thetaep.py 프로젝트: CCheng1231/A405
def thetaep(Td, T, p):
    """
    thetaep(Td, T, p)

    Calculates the pseudo equivalent potential temperature of a
    parcel. 


    Parameters
    - - - - - -
    Td : float
        Dewpoint temperature (K).
    T : float
        Temperature (K).
    p : float
        Pressure (Pa).


    Returns
    - - - -
    thetaepOut : float
        Pseudo equivalent potential temperature (K).


    Notes
    - - -
    Note that the pseudo equivalent potential temperature of an air
    parcel is not a conserved variable.


    References
    - - - - - -
    Emanuel 4.7.9 p. 132


    Examples
    - - - - -
    >>> thetaep(280., 300., 8.e4) # Parcel is unsaturated.
    344.99830738253371
    >>> thetaep(300., 280., 8.e4) # Parcel is saturated.
    321.5302927767795
    
    """
    c = constants();
    if Td < T:
        #parcel is unsaturated
        [Tlcl, plcl] = LCLfind(Td, T, p);
        wv = wsat(Td, p);
    else:
        #parcel is saturated -- prohibit supersaturation with Td > T
        Tlcl = T;
        wv = wsat(T, p);
    
    # $$$   disp('inside theate')
    # $$$   [Td,T,wv]
    thetaval = theta(T, p, wv);
    power = 0.2854 * (1 - 0.28 * wv);
    thetaep = thetaval * np.exp(wv * (1 + 0.81 * wv) \
                                   * (3376. / Tlcl - 2.54));
    #
    # peg this at 450 so rootfinder won't blow up
    #
    if(thetaepOut > 450.):
        thetaepOut = 450;
    return thetaepOut
예제 #29
0
def isotope_calcite(d, TC, pCO2, pCO2cave, h, V, phi, d18Oini,tt):
    #boundary value constant parameters (equiv of BOUNDARY)
    R2smow = 0.00015575
    R18smow = 0.0020052
    R18vpdb = 0.0020672
    
    eva=evaporation.evaporation(TC, h, V)   #Evaporationrate (mol/l)
    fracs=cmodel_frac.cmodel_frac(TC)       #Fractionation factors
    TK = 273.15 + TC            #Absolute temperature (K)
    #Tau precipitation (s); t=d/a (according to Baker 98)
    Z = 0.0001/(1.188e-011 * TC**3 - 1.29e-011 * TC**2 + 7.875e-009 * TC + 4.844e-008)           
    alpha = (1.188e-011 * TC**3 - 1.29e-011 * TC**2 + 7.875e-009 * TC + 4.844e-008)
    #Tau buffering, after Dreybrodt and Scholz (2010)
    T = 125715.87302 - 16243.30688*TC + 1005.61111*TC**2 - 32.71852*TC**3 + 0.43333*TC**4      
    
    #Concentrations and mol mass
    #Concentrations of the spezies in the solution, with respect to soil pCO2
    outputsoil = constants.constants(TC, pCO2)  
    #Concentrations of the spezies in the solution, with respect to cave pCO2
    outputcave = constants.constants(TC, pCO2cave)           

    HCOSOIL = outputsoil[2][2]                   #HCO3- concentration, with respect to soil pCO2 (mol/l)    
    HCOCAVE = outputcave[2][2]/math.sqrt(0.8)    #HCO3- concentration, with respect to cave pCO2 (mol/l)
    
    #Mol mass of the water, with respect to the volume of a single box (mol)
    h2o_ini = 0.1/18            
    #Mol mass of the HCO3-(soil), with respect to the volume of a single box (mol)
    hco_ini = HCOSOIL*1e-4 
    #Mol mass of the HCO3-(cave), with respect to the volume of a single box (mol)    
    hco_eq = HCOCAVE*1e-4       

    #Fractionation facors for oxygen isotope
    eps_m = fracs['a18_m'] - 1                                                                  
    avl = (-7356./TK + 15.38)/1000. + 1
    abl = 1/(fracs['e18_hco_h2o'] + 1)
    a = 1/1.008
    f = 1/6.
    
    Rdrop18_w = ( (d18Oini / 1000.) + 1) * R18smow
    Rdrop18_b = Rdrop18_w / (fracs['e18_hco_h2o'] + 1)
    Rv18 = avl * Rdrop18_w
    
    # Definition of the input-parameter of the program "O18EVA" at the time
    # t=0s, e.g. at the beginning of the mix process

    hco_mix = hco_ini
    h2o_mix = h2o_ini
    HCOMIX = hco_mix / 1e-4

    r_hco18_mix = Rdrop18_b
    r_h2o18_mix = Rdrop18_w

    number = 0

    r18res = 0
    r18mix = 1
    
    while r18mix != r18res:
    
        number += 1
        
        r18_hco_res = r_hco18_mix
        
        temp = O18EVA.O18EVA(d, TC, pCO2, pCO2cave,  h, V, r_hco18_mix, r_h2o18_mix, Rv18, HCOMIX, 
        h2o_mix,tt)

        hco_out = temp[3]                       #mol mass of hco
        h2o_out = temp[5]                       #mol mass of h2o
        
        r_hco18_out = temp[0]                   #oxygen isotopic ratio of hco
        r_h2o18_out = temp[1]                   #oxygen isotopic ratio of h2o
        
        #%%% 1) simple mixprocess
        hco_mix = phi*hco_ini + (1-phi)*hco_out                 #mixing of hco
        h2o_mix = phi*h2o_ini + (1-phi)*h2o_out                 #mixing of h2o
        
        phi_r_b = 1 / (1 + (1-phi) / phi*hco_out*hco_ini)       #isotopic mixing parameter of hco
        phi_r_w = 1 / (1 + (1-phi) / phi*h2o_out/h2o_ini)       #isotopic mixing parameter of h2o
        
        r_hco18_mix = phi_r_b*Rdrop18_b + (1-phi_r_b)*r_hco18_out        #new oxygen isotopic ratio of hco
        r_h2o18_mix = phi_r_w*Rdrop18_w + (1-phi_r_w)*r_h2o18_out        #new oxygen isotopic ratio of h2o
        
        H2O_mix = h2o_mix*18/1000.      #mol -> l (mol*(g/mol)/(g/kg)*(l/kg)
        HCOMIX = hco_mix / H2O_mix     #new hco condentration
        
        #end of the extended mixprocess
        
        r18mix = round(r_hco18_mix*10**13)
        r18res = round(r18_hco_res*10**13)
        
    temp = O18EVA_MEAN.O18EVA_MEAN(d, TC, pCO2, pCO2cave, h, V, r_hco18_mix, r_h2o18_mix, Rv18, 
    HCOMIX, h2o_mix,tt)
    
    r_hco18 = np.array(temp[0])
    hco = np.array(temp[2])
    
    delta_1 = np.array(temp[4])
    delta_0 = delta_1[0]
    delta_end= delta_1[-1]
    
    r_h2o18 = np.array(temp[1])
    h2o = np.array(temp[3])
    
    tmp = np.isnan(r_hco18)
    if tmp.all() != True:
        
        r_hco18_mean = sum( (r_hco18[:-1] + np.diff(r_hco18,n=1)/2.) * (-np.diff(hco,n=1) / (hco[0]-hco[-1]) ))
        d18Ocalcite = (r_hco18_mean*(fracs['e18_hco_caco'] + 1)/R18vpdb - 1)*1000

        r_h2o18_mean = sum( (r_h2o18[:-1] + np.diff(r_h2o18,n=1)/2.) * (-np.diff(h2o,n=1) / (h2o[0]-h2o[-1]) ))
        d18Owater = (r_h2o18_mean/R18smow - 1)*1000

        d18Ovapor = (Rv18/R18smow - 1)*1000

        return d18Ocalcite
    
    else:
        return [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN]
예제 #30
0
파일: RapTorus.py 프로젝트: kismir/RapTorus
from threading import Thread
import time
import sys
import os
# add module folders to path
sys.path.append(os.getcwd()+'/Gmodule')
sys.path.append(os.getcwd()+'/MSHmodule')
import gExtract
import mshExtract
from MainFrame import MFrame
from constants import constants

#initializing vizulization constants for model and also variables space
cons=constants()
print('constants initialized')

## open stl file
print('exctracting geometry from file')
path='D:/tre.stl'
model,cmass=gExtract.eSTL(path) # model=[[normal,vecn1,vecn2,vecn3],... ](triangles); cmass = (x,y,z)
print('stl surface elements: ',len(model))

##assign geometry
cons.vect=model
cons.cmass_xyz=cmass
cons.Gwidgets.append('geometry')
print('model assigned to constants')

## open mesh file
#print('exctracting geometry from file')
#path='D:/el_ex.txt'
예제 #31
0
파일: main.py 프로젝트: westerhack/Quandary
from constants import constants
from node import node, getiter
from knowndict import knowndict
n = node(constants())
with open('qfiles/testcode.qq') as f:
    gen = getiter(n.consts, f.read())
known = knowndict(n.consts)
print('----')
print(n.evalnode(gen, known), known)
print('----\n')
if __debug__ and '$dnd' not in known:
    print(known, end = '\n--\n')
    print(repr(known))
예제 #32
0
def wsat(Temp, press):
    """
    wsat(Temp, press)

    Calculates the saturation vapor mixing ratio of an air parcel.

    Parameters
    - - - - - -
    Temp : float or array_like
        Temperature in Kelvin.
    press : float or array_like
        Pressure in Pa.

    Returns
    - - - -
    theWs : float or array_like 
        Saturation water vapor mixing ratio in (kg/kg).

    Raises
    - - - -
    IOError
        If both 'Temp' and 'press' are array_like.

    Examples
    - - - - -
    >>> wsat(300, 8e4)
    0.028751159650442507
    >>> wsat([300,310], 8e4)
    [0.028751159650442507, 0.052579529573838296]
    >>> wsat(300, [8e4, 7e4])
    [0.028751159650442507, 0.033076887758679716]
    >>> wsat([300, 310], [8e4, 7e4])
    Traceback (most recent call last):
        ...
    IOError: Can't have two vector inputs.

    """
    c = constants();
    es = esat(Temp);

    # We need to test for all possible cases of (Temp,press)
    # combinations (ie. (vector,vector), (vector,scalar),
    # (scalar,vector), or (scalar,scalar).
    
    try:
        len(es)
    except:
        esIsVect = False
    else:
        esIsVect = True

    try:
        len(press)
    except:
        pressIsVect = False
    else:
        pressIsVect = True
    
    if esIsVect and pressIsVect:
        raise IOError, "Can't have two vector inputs."
    elif esIsVect:
        theWs = c.eps*es/(press - es)
        #theWs = [(c.eps * i/ (press - i)) for i in es]
        # Limit ws values so rootfinder doesn't blow up.       
        #theWs = list(replaceelem(theWs,0,0.060))
    elif pressIsVect:
        theWs = c.eps*es/(press - es)
        #theWs = [(c.eps * es/ (i - es)) for i in press]
        # Limit ws values so rootfinder doesn't blow up.       
        #theWs = list(replaceelem(theWs,0,0.060))
    else: # Neither 'es' nor 'press' in a vector.
        theWs = (c.eps * es/ (press - es))
        # Limit ws value so rootfinder doesn't blow up.
        if theWs > 0.060: theWs = 0.060
        elif theWs < 0: theWs = 0

    # Set minimum and maximum acceptable values for theWs.
        
    try:
        len(theWs)
    except:        
        if theWs > 0.060: theWs = 0.060
        elif theWs < 0: theWs = 0
    else:
         theWs[theWs < 0] = 0
         theWs[theWs > 0.060] = 0.060
    #    theWs = list(replaceelem(theWs, 0, 0.060))

    return theWs
예제 #33
0
#import matplotlib as mpl
#mpl.use('Agg')
from pylab import *
import os, sys
import traceback
from constants import constants
(h, k, c, Tcmb) = constants()

# change log
# v0.4 Added capability in getAtmosphere to define a custom transmission file


class NETlib():
    """
    class with all necesary libraries to compute bolometer NET

    """
    def __init__(self, verbose=True):
        """

        symlink from NETlib.py to the latest version NETlib_v0.X.py

        """
        self.path = '/n/home01/dbarkats/work/20170801_S4_NET_forecast_python/'
        self.amversion = 9.2
        self.verbose = verbose
        self.orig_stdout = sys.stdout
        self.getVersion()
        #if self.verbose==False:
        #    self.f = open('outputs.txt','w')
        #    sys.stdout = self.f
예제 #34
0
"""
Author:
Benjamin Hills
University of Washington
Earth and Space Sciences
April 28, 2020
"""

# Import necessary libraries
import numpy as np
from scipy import sparse
from scipy.integrate import cumtrapz
from scipy.interpolate import interp1d
from supporting_functions import analytical_model, viscosity, Robin_T
from constants import constants
const = constants()


class numerical_model():
    """
    1-D finite-difference model for ice temperature based on
    Weertman (1968)

    Assumptions:
        1) Initialize to 1-D Analytical temperature profile from either Robin (1955) or Rezvanbehbahani et al. (2019)
            then spin up the numbercal model to steady state until all points are changing by less then 'tol' every time step.
        2) Horizontal velocity
            Shear stress for lamellar flow then optimize the viscosity to match the surface velocity.
        3) Vertical velocity
            Two options:    first is to use an exponential form as in Rezvanbehbahani et al. (2019)
                            second is to use the shape factor, p, as from Lliboutry
예제 #35
0
# from netCDF4 import Dataset
# import matplotlib.pyplot as plt
# import glob
# import numpy as np
# import matplotlib
# import matplotlib.cm as cm
# import SAM_init_plot.block_fns
# import SAM_init_plot.misc_fns
# from SAM_init_plot.misc_fns import raddist, radprof
# from SAM_init_plot.block_fns import blockave2D, blockxysort2D, xysort
# from thermolib.constants import constants


#plt.rc('text', usetex=True)

c = constants()

plt.close('all')

def expfunc(x, a, b, c):
    return a*np.exp(-b*x) + c

matplotlib.rcParams.update({'font.size': 28})
matplotlib.rcParams.update({'figure.figsize': (18, 12)})
matplotlib.rcParams.update({'lines.linewidth': 3})
matplotlib.rcParams.update({'legend.fontsize': 24})
#matplotlib.rcParams.update({'mathtext.fontset': 'custom'})
matplotlib.rcParams.update({'mathtext.fontset': 'cm'})
#matplotlib.rcParams.update({'font.family': 'serif'})

plt.style.use('seaborn-white')
예제 #36
0
파일: theta.py 프로젝트: CCheng1231/A405
def theta(*args):
    """
    theta(*args)

    Computes potential temperature.
    Allows for either T,p or T,p,wv as inputs.
    

    Parameters
    - - - - - -
    T : float
        Temperature (K).
    p : float
        Pressure (Pa).


    Returns
    - - - -
    thetaOut : float
        Potential temperature (K).


    Other Parameters
    - - - - - - - - -
    wv : float, optional
        Vapour mixing ratio (kg,kg). Can be appended as an argument
        in order to increase precision of returned 'theta' value.
    
    
    Raises
    - - - -
    NameError
        If an incorrect number of arguments is provided.
    
    
    References
    - - - - - -
    Emanuel p. 111 4.2.11


    Examples
    - - - - -
    >>> theta(300., 8.e4) # Only 'T' and 'p' are input.
    319.72798180767984
    >>> theta(300., 8.e4, 0.001) # 'T', 'p', and 'wv' all input.
    319.72309475657323
    
    """
    c = constants();
    if len(args) == 2:
        wv = 0;
    elif len(args) == 3:
        wv = args[2];
    else:
        raise NameError('need either T,p or T,p,wv');
    
    T = args[0];
    p = args[1];
    power = c.Rd / c.cpd * (1. - 0.24 * wv);
    thetaOut = T * (c.p0 / p) ** power;
    return thetaOut