0% found this document useful (0 votes)
9 views12 pages

Example

It's just an example.

Uploaded by

Athar Smart
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
9 views12 pages

Example

It's just an example.

Uploaded by

Athar Smart
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
2/9/24, 04 PMA hater in codes ko separetely smja den achy se. ‘om [Link] import minimize scalar, root, scalar, solve import [Link] as CP import CoolPrap import numpy 35 np © career Certainly! Ler's break down each part ofthe code and explain is functionality Importing necessary libraries/modules fron [Link] inport wininize_sealar, root_scalar, frolve! This ie imports specific optimization functions from the [Link] module, These functions are usd for scalar minimization (nintatze seater) finding roots of scalar functions (reet_sealar), and solving systems of non-linear equations (fselv. Anport [Link] as cP: This imports the CoolProp library, whichis used for thermephysical property calculations under the alas cP. Amport coolProp: This imports the entire CoelProp module Anport ninpy a6 mp This imports the NumPy library under the alias mp, which commonly used {for numerical computing in Python “These imports make avaliable various functions and tools for optimization, thermophysicl property calculations, nd numerical computations Is there anything specific you'd like to know about these imports or ther functionalities? Ow in codes ko bhi separately smja den._def props_ NHBH2O(T=None, P=None, Q=None, X=None, UsNone, H=None, $=None, O=None} Calculates properties for an ammonia-vater mistre using CoolProp/REFPROP. Ags T float): Temperature in Kelvin P (oat: Pressure in Pascal Q (heat): Quality (vapor fraction, X loa: Mole fraction of ammonia (between O and 0), U float: Internal Energy in J7kg-K H (float: Enthalpy in rk 5 (loa: Entropy in kg-K D float: Density in kg/m Retums ict Dictionary containing requested properties and their values © coatcor Here's a breakdown of the function props_ Maho nitps:[Link].comiel9a7c50e-5043-4a4e-0380-278942042109 ne 2/9/24, 04 PMA hater ef pros_wsn20(1 one): This line one, PaNone, Qevone, XoNone, Unione, HoNone, SeNone, defines a function named props, mlaa0 that takes in several parameters representing properties of an ammonia-water mibcure, These parameters are optional and can be passed tothe function for property calculations. * s. SH-THsib a docstring, a muli-ine string enclosed in tiple quotes, which provides documentation fr the function. It explains the purpose of the function is arguments, and the properties it retums. -rgst: This section ofthe docstring Ist the arguments (parameters) thatthe function can accept along with thelr descriptions, Returns: This section ofthe docstring explains what the function retuins In this case, it retuns 2 dictionary containing the requested properties and ther values. The function appears tobe designed to calculate various thermodynamic properties of an ammonia water minture using CoolProp or REFPROP.f accepts parameters lke temperature, pressure, qual ‘mole fraction of ammonia, internal energy, enthalpy, entropy, and density, and returns a ditionary containing the calculated properties Would you lke further clrfiation on any specific aspect ofthis function? You hrline ko separately smiein...y args kia hoty ye bhi..kl empty space aey wo bhi cchatcPr Certain! ‘break down each pat of the function definition and its documentation ‘et props_Nan20: This line bagins the definition of a function named preps_N¥aK20. Functions in Python are defined using the det keyword (Tonone, Petone, GoWone, XeNone, Untone, Hone, Satine, OeNone): These are the parameters (or arguments thatthe function accepts. Each parameter represents a specific property ef an ammonia ‘water mixture of None if not provided. Here's what each parameter stands for perature in Kevin. Pressure in Pascal. Quality (vapor fraction) Mole fraction of ammonia ( Enthalpy nko, « Internal Energy in /kg-K Entropy inka Density in kg/m. These parameters allow the caller to speciy the properties for which they want to calculate the nitps:[Link].comiel9a7c50te-5043-4a4e-0360-278942042109 ane 2/9/24, 04 PMA hater so: Thisie a docstring 2 sting literal that occurs 9s the first statement in 2 module, function, clas, or method definition. t provides documentation forthe function. Calculates properties for an anmoniaewater ninture using CoolProp/REF?ROP.: This isa 1 function does. description of wi ‘avast: This a section header in the docsting indicating thatthe subsequent lines describe the function's arguments 1 (float): Temperature Sn Kelvin. This ine explains thatthe parameter ¥ should be a float representing temperature in Kelvin, Similar explanations follow for ather parameters, Aeturns::Thisisa section header inciating thatthe subsequent ine describes what the function ‘let: Dictionary containing requested properties and thetr values.: This line explains thatthe function retums a dictionary containing the requested properties and ther values. These comments and documentation serve to clarity the purpose ofthe function and the meaning of its parameters and return values. Let me know ifyou need further explanation Ow in cones ko bhi separately sjsein..# Check f atleast 3 properties are given given_propertis = 17, 9, .X,U,H,S, O] rum, given. properties = sumiprop is not None for prop in given_propertis) if pum given_properties «3: ‘aise ValueFrror’At least 3 properties must be specified”) # Setup the state for ammonia-water misture PROP, ‘NHBBH209 © cracer Here's a breakdown of the code snippet you provided ee ee 1 check $F at Least 3 properties are given: This is 3 comment line indicating the purpose of the folowing code block Ty Py @ Xs Us My Sy 0): This line creates alist called given, properties iven_properties Containing the values ofall the properties provide as arguments tothe function, fun_given properties = sun(prop 1s not None for prop in given properties): Ths line calculates the number of properties that are nat None using a generator expression within the nitps:[Link].comiel9a7c50te-5043-4a4e-0360-278942042109 ane 2/9/24, 04 PMA hater sun() function, It counts the number of properties that have been provided by the use. 16 run_given_properties « 3:: This line checks ifthe numberof given properties slss than 3 raise Valueteror(*At least 3 properties aust be specified."):If fewer than three properties 2re provided, this ine raises a valuetrroe with the specified message, indicating that atlas three properties must be specied State = cP-abstractstate(‘REFPROP", "WHBH20"): This line Sets up the state for an ammonia water macure using CoolProp’s Abstractstate clas with the mixture defined as'NH26H20 using the 'REFPROP' backend, This code segment ensures thatthe user provides at least three properties fr the ammonia-water rire calculation, If not, it aes an error. Then, it sets up the state for the ammonia-water misture using CoolProp. Let me know ifyou need further clarification on any par af the code! You Ura ht form men achy se hr ine ko smjacin cchatcPr Yaqeenan! Yohan code ka har hissa Urdu mein samy ja raha ha eee a ror ony pre | Kan az kaw 3 properties di gayi hain ki janch karen: Yoh ek tafsl yadgar hal jo darust karma chata hai ke agle code block ki maga ys ha AL gnyL properties = (1, Py Q X Us Hy S, 9]: Yeh line ek list banat hai jo (41_gey properties ke nam shai aurizmin function ke arguments mein di gayi properties ki values hamil hot hain tun_ds_gayi_properties = sun(prop 4s not None for prop in di_savi properties): Yeh line generator expression ka itemal karte hus gair done properties kitadsad ka shumar karti hal. Ye san() function ke andar ek generator expression stem kar ke di gayi properties mein se gale one ki tadad ko shumar kart ha 4 rum_d4_gay$_ properties < 3:: Yel ych check arta hai ke di gayi properties ki tadaad teen se kam hal ya nai raise Valueteror("Kan az kam 2 properties ka tatruf Karns zaroord. hal"): Agar teense kam properties di gayi hain to yeh line Valuetrror that hal jiske sath di gayi message hot hal. Yen batata hai ke kam az kam teen properties ka taaruf kama zaroor hal State = cP-Abstractstate(‘REFPROP", "WwB4:20"): Yeh line CoolProp ke AbstractState las ka istemal kat hai aur ammonia-paani mishran ke lye halat ko tayyar kart hai REFPROP" backend ka istemal kar ke. ‘Yeh code hissa yeh darustkarta hai ke stemalkarne wala kam 22 kam teen propertias ko ammonia-paani mishran ke hisaab se diya hai ya nahi, Agar nah, to yeh ek ghaltiuthata hs. Pit yeh ammania-paani mishran ke lie halat ko CoolProp ke sath tayyar kata hal ‘Agar kis bhi code ke hise mein mazeed tafseel chahye, ta zarcor bataen! nitps:[Link].comiel9a7c50te-5043-4a4e-0360-278942042109 ane 2/9/24, 04 PMA hater Ow ln codes ko bhi sepaartly chy se smjacin..ASet up the property knoledge inputs_all = [(T\CPIT.T, (P: CPAP), CQ, CPIA, Q(X None, ), (U, [Link] CH Cinmass, Hy (S, CPiSmass, 9), (DY, CPiOmass.)] inputs. given =I([Link].a for (sepva) in inputs all iva is not None] inputs xx = [[Link] for (tcp val) in inputs_gven if st!= XX] ‘ocaleep = [sep frit ep val in inputs. alif tcp, val) notin inputs given and x’ notin © chatcer Let me break down the code snippet you provided Anputs_aia: This line creates alist of tuples where each tuple contains a property name, 9 CoolProp constant, andthe corresponding value the value is None, it means that propery isnot provided Anputs_aiven: This line creates another lst of tuples by iterating ever Anputs_sl and filtering out tuples where the value isnot Noe, meaning those properties ae given, Anputs_sx: This line further filters Anputs_given to exclude the property, whic represents the mole {rection of ammonia, tocale_¢p: This line creates ast of tuples for properties that need to be calculated: I iterates over Anputs_al1 and adds tuples where the value is not provided and the propery is not'X" (mele faction of ammonia) Here's a brie summary of exch list Anputs_ali: Contains all properties with their associated values or None inputs given: Contains properties that ae provided (values are not Hone nputs_xx: Contains provided properties excluding the mole faction af ammonia, ‘ocale_ep: Contains properties that need to be calculated. This code segment seems to be par of a larger context where properties ofa substance or mixture are beeing managed and ealulated,licly using the CoolProp library Hf you need further explanation or have any question, fel fee to ak! Ow ye tuples kia hoty © chacer ‘ples are fundamental data structure in Python that are sed to store an ordered collection of items “They are similar to lists but are immutable, meaning ther elements cannot be changed ater they are created, Tuples ae defined using parentheses In the context ofthe code snippet you provided, tuples are being used to organize related pieces of information together, Let's break down what each tuple represents: nitps:[Link].comiel9a7c50e-5043-4a4e-0380-278942042109 siz 2/9/24, 04 PMA hater ee a ea) on Coren nea Here, each tuple in inputs_all represents a property of a substance or miture. The tuples contain ‘The property name: 1" UH 8,0 ‘The CoolProp constant associated with the property For instance, CPT, CPAP, CP4Q, Mone, CP. sess, The value ofthe property For example, 77.8% UK 5.8 “These tuples are used to organize information about different properties ina structured manner. For Instance, the fist tuple (', ¢B.47, 1) indicates thatthe property (temperature) i being represented, ts CoolProp constant i e947, and its value is Throughout the code, these tuples are accessed and manipulated to perform property calculations ot ‘checks, as demonstrated by the subsequent lines of code you provided It you have any further questions or need additonal clarification, please fel fee to ak Ow in codes ko bhi separately smiaein..# Set mole fractions Xs given, otherwise iterate if Xs not None! State set_mole factions, 1 =X) lee: def X tend ass, State, input Stateset mole factions\X ass, 1-X ass) State build_phase_ervelopet"") UP = CP.generate_update_pairinputs xx], inputs x0} inputs x1], inputs x1), ry State updateUP(0, UPLT}UPI2) tu. = inputs 2] ost uu = State keyed outputiuu_ sit) return est uv-wu pi2] © career Here's a breakdown of the code snippet you provided Eereeeranee eran tr? anrarenarren Sonera renertnen oy Pret rnet cpeererenpe irr Svtierrivtrer ihe eee a enan ieee ae come Ta eernsntete ey] 46 X 45 not None: This ine checks if the value of x (male fraction of ammonia) isnot None Tis provided, it means thatthe mole fractions can be directly set, State. set mole fractions((X, 4 ~ X]):1FXis provide this ine sets the mole factions using the provided value of x and calculates the complementary mole fraction for water {I~ x) ‘eleer: If xis not provided ie. itis Hon) this block of code is executed, ef X Ater([Link], State, Anput_xx)s: This line defines 3 function named x Aker that takes thee arguments: ass (stumed mole fraction of ammonia}, state (CoolProp state object), and Anput_xx nitps:[Link].comiel9a7c50te-5043-4a4e-0360-278942042109 ena 2/9/24, 04 PMA hater (ist of properties to erate). e the X ster function [Link] tole fractions((Xa85, 4 ~ Xes8}):This sets the mole fractions using the assumed value of ase state. build_phase_envelope(“") Tis bulds the phase envelope forthe state UW? = ce-generate_upéate_patr(inputs so(O](2]+ Inputs xx(6)[2]> Anputs x12), Anputs_xx(1}{2}): This generates an update pair based of the provi «properties in Anput_xx [Link](uP{@], UPI], UP[2]): Ths updates the state based on the generated update pai. up = Snputs_wx(2I: This exacts the property to be iterated upon from Snput_x cest_u = [Link] output (uu p(3)): This estimates the valu ofthe property to be iterated sing CootProp, return est_uu - uu_p{2I: This returns the difference between the estimated property value and the target property value, which is used for iteration Thi cx egmen' her sets the mole fractions directly fxs provided or detines an iteration function if xis not provided, allowing the male fraction of ammonia tobe determined iteratively, Ht you have any further questions or nee additonal carifeation, please feel fee to ask Ow 1), x0 = Or method="toms748'rtel = 1e-12) X-= sal{root] State set_ mole fractions(X,1~X) State buld_phase_ervelope") Statebuld_phase envelopes") UP = cP generate_update_pairinputs 9} inputs (02), inputs x1), inputs »1)/2) State update(UP(O}UP(1}.UPI2) resuk = 0 1des ko bhi separately smjaein..sol = root, scalar iter, stgs=(State, inputs, brack © chatcer Here's a breakdown of the provided code ee ee te See eee eee Cee ere eases Se ee roe eT Oe Utena oC] eereneee error rene Te) ere taeas Let's go through t step by step sol = root_scalar(X iter, arges(Stete, Snputs_nx), brackets[O, 1], x8:8.2, wethode"toms748", rtotene-22): This line uses a finding algorithm (rast_seatar) to find the root ofthe function ster. The parameters passed to reot_sealar include: X ster: The function to find the root of argse(State, snputs_10: Additional arguments required by the function x seer. brackets[0, 21: bracketing interval within which the root is expected tole 3020.1: An intial guess forthe root rethodetons748': The method used for root finding tolate-12: The relative tolerance forthe root. X = soll ‘reat"]: This ine retrieves the root found by the root_scalar algorithm and assigns it to the variable x nitps:[Link].comiel9a7c50te-5043-4a4e-0360-278942042109 2/9/24, 04 PMA hater State.set_sole_fractions([X, 2 ~ XI): Sets the male rations based nthe root found by the algorithm ‘State. ut2d_phase_envelope(*"): Builds the phase envelope forthe state Builds the phase envelope forthe state again, possibly redundant or intended for addtional safety, > = [Link] update pair(inputs o(6](2], inputs x[0](2]+ Anputsx(2)(2], Anputs ect) 21): Generates an update pair based on the provided proper in input_ex ‘state. update(UP(0], UPI], UP[21): Updates the state based on the generated update pat ‘Initializes an empty dictionary for storing results This code segment essentily finds the root ofthe X Aker function, which s responsible for iteratively determining the mole fraction of ammonia. Then, it updates the state variables based an the calculated mole fractions and generates a phase envelope, Ifyou have any further questions or need adltona ication, please fee ee to as @ ww in codes ko bhi separately [Link] resubist} = State keyed_outputcn) in [Link] fer steayal ininputs giver: result} = val resukX] =X © cater Here's a breakdown of the provided code This loop iterates over each tuple (st, ep) inthe list tocale_¢p. Each tuple represents a property st with its associated CoolPrap constant ep. State. keyed_output (cp): This line fetches the value af the property represented by the CoolProp constant ep using the CoolProp state object state result{st state.keyed_output(cp): Ths line assigns the fetched value to the property name tin the resuit dictionary Reece sess his loop iterates over each tuple (St, eps val) inthe lst nputs_given. Each tuple represents a property st its associated CoolProp constant ep, andi given value val result{st ‘si: Ths ine assigns the given valve val tothe property name st inthe result dictionary, Tis line assigns the calculated value of male fra +X key in the result dictionary. nitps:[Link].comiel9a7c50te-5043-4a4e-0360-278942042109 ene 2/9/24, 04 PMA hater Im summary, these loops are used to populate the result dictionary with the calculated and given properties, It Rerates over the properties that need to be calculated (tocale_ep) and assigns their values using CoolProp. Then it iterates over the given properties (inputs given) and directly sesgns their values. Finally it assign the calculate mole fraction x tothe ‘x’ key inthe result dictionary, H¥ you have any further questions or need! addtional clarification, please fel fee to ak Ow in codes ko bhi separately snjaein..ifresult(Q!] > 1 or result} < [WE = "REFPROP:NH3}"striresul{X)+"JGHOY"steT-resut XD) + hg = CP PropsSi(H,Presuk'P] 0°.) hfs CPPropsSi(H PresukP] 00.) hig = hg - ht Lnaw = (result) - hfs resut?Q] = round\@_new3) sorted, result = (key: resubikey] for key in [TQ XU Hy St Dp result © coaster Let's break down the provided code snppe his block of code checks if the quality @'s outside the valid range (ie, greater than 1 or less than 0) $0, itrecaleulates the qua based on enthalpy: oa “este result Xo" “este (Seresult{ X'])*"]":Thisline defines 3 working fli (misture of NH3 and H20) based on the calculated mole fraction x, he = €[Link](‘H,'P* result ‘P,Q! ANF): This calculates the specific enthalpy of saturated vapor atthe given pressure result{"P"). NF = [Link]((W","P" rest 'P'],'@",@,AF): This calculates the specific enthalpy of saturated liquid at the given pressure resute{‘P') ig = hg ~ hf This calculates the specific enthalpy of vaporization new = (results"H"] ~ RFD / fg: This recalculates the qualty based on the enthalpy resstt{"#'] ‘the specific enthalpy of saturated liquid nf, and the specific enthalpy af vaporization We result{"Q') = round(@_new, 3): This assigns the recalculated quality to the result{"] ater rounding it to three decimal places sorted_result: This ne creates a dictionary containing a subset of properties ("T', '@, "Q's "X's "Us, (Hs 'S', ‘0° fom the result ditionay. return sorted result: This line returns the sorted_resuit dictionary containing the selected properties. nitps:[Link].comiel9a7c50te-5043-4a4e-0360-278942042109 one 2/9/24, 04 PMA hater In summary, this cade snippet ensures thatthe quality @ falls within the valid range (0to 1) by recalculating it based on enthalpy if falls outside this range. then retums a ditionay containing a subset of properties with the recalulated quality. None, Q=None, X=None, fone, H=None, S=None, D=Nonel Calculates properties for an ammonia-water misture using CoolProp/REFPROP, Ags (float: Temperature in Kein, P (oat: Pressure in Pascal Q (oat): Quay (vapor fraction) X loa Mole fraction of ammonia (between O and 1), U float: Internal Energy in 7kg-K H oat: Enthalpy in kg 5 (oat) Entropy in kak D float: Density in kg/m. Retums Ait Dictionary containing requested properties and their values + Check f atleast 3 properties ave given given_propedis = (7,8, 2X. U,H,S, 0] hum. given_properties = sumiprop is not None for prop in given_propertis) if num given properties <3: raise Valuettror Atleast 3 properties must be specified”) 1 Setup the state for ammonia-water mixture State = CP AbstractStatefREFPROP, ‘NH38H209 {Sot up the property knoledge inputs all = [(T\CPAT.T, (P: CPAP), CO, CPIO, 2, (XY None, X), (UY [Link], U), CiMieass, Hy, (S), CPISMmass, 9), (D CPOmass )) Inputs_given =[([Link] for fstcpval) in inputs alli val is not None ] inputs 2 = [[Link] for (tepyval) in inputs given fst = ‘tocaleep = [step frit ep val) in inputs. alif scp, val) notin inputs given and’ notin st, 1 Set mole fractions if Xs given, otherwise iterate if Xs not None: State set_mole factions, =X) lee def X ter ass State, input State set_mole factions(X ass, 1-X ass) State.buld_phase_ervelopet"") UP = cP.generate_update_pairinputs xa], inputs (02) inputs ee 1 inputs aft) ry State update(UP(0,UPLT}UPI2) u.p = inputs 2] ost uu = State keyed outputtuy_ it) return est u-wu pi2] sol = root stalarX ter, args=(State, inputs}, bracket=[0, 1) x0 0.1 method= toms748}.tl = 12-12) X= solftoot] Stateset_mole factionsiX, 1 -X) State build_phase_ervelope(") State build_phase_ervelope(") UP = CP.generate_update_pairinputs xf] inputs o(0}2. inputs x17), inputs xa) nitps:[Link].comiel9a7c50te-5043-4a4e-0360-278942042109 sorte 2/9/24, 04 PMA hater State update{UPIO}UPLT}.UPI2) resuk =) for step in toca. cp result} = State keyed outputen} for stepwalin inputs give: resukt} = va resukx] =X if resui('Q1 > 1 or es WE = "REFPROP-NH3}"strresuTX)}="JQH2OY"ssteT-resut + CP Propssi( result PYF) hi hf= CPPropsSI(H, Presuk(P]'0°[Link]) hig = hg - hf OLnew = (result) - hyn resuk/Q] = round@_new3) sorted, result = key: esubikey]forkey in [TQ XY UH, SDI) return sorted result © coarcer his function props_ wisi calculates properties for an ammonia-water mixture using CoolProp/REFPROP. Let's break clown the function: Function Definition and Documentation: ‘The function is defined with the name props. sano, Ietakes several parameters representing diferent properties ofthe mixture: Temperature (0 Pressure e), Quality (Q, Mole fraction of ammonia 0g, Intenal Energy (Y,Enthalpy Entropy (Si and Density, The function returns a dictionary containing the requested properties and ther values. ‘The documentat Property Validation: Ie checks ita least three properties are given I fewer than three properties are specified it 3m expins the purpose ofthe function and the meaning of ts arguments Setting Up the State and Property Knowledge {or the ammonia-water mixture using CoolProp’s Abstractstate class. Iesels up the stat Ieiniitize sts tnputs_o12, nputs_ given nputs_xx and tocale_ep to organize property information, Mole Fraction Handling: Irthe mole fraction xs provided, it sets the mole Fractions direct using the given value, (Otherwise, iteratively calculates the mole fraction using the X_ster function, which s defined inside the function Property Calculation: Ir caleulstes propertis that need to be computed using CoolPrap functions and updates the result dictionary Quality Recalculation Ie checks ifthe quality @s outside the valid range (to 1). Iso, it ecalculates the quality based on enthaloy and updates the result dictionary Sorting and Returning Results: Ie sonts the properties in specific order and return ther in a dictionary format (Overall, the function is 9 comprehensive tool for calculating various properties of an ammenia~ water midure, handling diferent scenarios such as direct property specification and iterative ‘aleulation of mole factions. It also ensures the accuracy and validity of the calculated properties, Ow nitps:[Link].comiel9a7c50e-5043-ta4e-0360-278942042%09 se 2/9/24, 04 PMA hater is puury ko python men ih den cchatPr Yeh raha pura code Python mein eee) au 4 snp See erent ener epeenanr capri aren virirene cine ti inner rpptebeieseiiessiynatrteen areata me eee a eer bene rete saree al Eereeersrn Ferner eerie een coarat Poe ees en ae arte eee rca 5 Perea Yoh code ammonia-water misture ke lye properties calculate karta hai using CoolProp/REFPROP brary. lsmein properties ko calcul kame ke lye various checks aur iterations hote hain. Agar kuch clarification chahiye ya aur koi saw ho, toh pooch sakte hain nitps:[Link].comiel9a7c50te-5043-4a4e-0360-278942042109 rane

You might also like