Best Python code snippet using grail_python
io.py
Source:io.py
1import matplotlib.pyplot as plt2from pleiades.analysis import *3class EQDSK(dict):4 def __init__(self,fname=None):5 if fname is not None:6 self.read_eqdsk(fname)7 else:8 pass9 def write_eqdsk(self,fname):10 with open(fname,"w") as f:11 pass12 def read_eqdsk(self,fname):13 with open(fname,"r") as f:14 pass15#class MirrorEQDSK(EQDSK):16# def __init__(self,fname=None):17# self["18#19#20# ## line 1 -- write grid information: cursign, nnr, nnz, nnv21# f.write(title+"".join("{:4d}".format(xi) for xi in [int(cursign),nnr,nnz,nnv]))22# ## line 2 -- write rbox,zbox,0,0,023# f.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [rbox,zbox,0,0,0]))24# ## line 3 -- write 0,0,0,psi_lim,025# f.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [0,0,0,psi_lim,0]))26# ## line 4 -- write total toroidal current,0,0,0,027# f.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [tot_cur,0,0,0,0]))28# ## line 5 -- write 0,0,0,0,029# f.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [0,0,0,0,0]))30def write_eqdsk(Rho,Z,psi,plas_currents,fname,title):31 title='PLEIADES '+title32 if len(title) >= 26:33 title = title[0:26]34 title = title.ljust(26) + "cursign,nnr,nnz,nnv = "35 nnr,nnz,nnv = int(len(Rho[0,:])),int(len(Z[:,0])),10136 rbox,zbox = np.amax(Rho)-np.amin(Rho),np.amax(Z)-np.amin(Z)37 tot_cur = np.sum(plas_currents)38 cursign = np.sign(tot_cur)39 blank = np.zeros(nnv)40 limit_pairs,vessel_pairs = 100,10041 rho0_idx = np.abs(Rho[0,:]).argmin()42 #### Plotting current and flux lines from plasma currents 43 [psi_lim] = locs_to_vals(Rho,Z,psi,[(.6,0)])44 psi_ves = psi_lim*1.0245 psi_levels = tuple(sorted([psi_lim,psi_ves]))46 fig,ax = plt.subplots()47 cf = ax.contour(Rho,Z,psi,psi_levels,colors='k',zorder=1)48 ## get contour for psi_lim boundary49 flpoints = get_fieldlines(cf,psi_lim,start_coord=(.05,.5),end_coord=(.05,-.5))50 r,z = flpoints[:,0],flpoints[:,1]51 z = np.array(list(z)+[-z[0]])52 z = z[::-1]53 r = np.array(list(r)+[r[0]])54 r = r[::-1]55 flpoints = np.vstack((z,r)).T56# ax.plot(flpoints[:,0],flpoints[:,1],"bo")57# ax.plot(flpoints[0,0],flpoints[0,1],"go")58# ax.plot(flpoints[-1,0],flpoints[-1,1],"ro")59# plt.show()60 fl_dist = get_fieldline_distance(flpoints)61 spl = UnivariateSpline(z,r,k=1,s=0)62 fl_spl = UnivariateSpline(fl_dist,z,k=1,s=0)63 uniform_s = np.linspace(fl_dist[0],fl_dist[-1],100)64 zlimit = fl_spl(uniform_s)65 rlimit = spl(zlimit)66# ax.plot(r,z,"bo")67# ax.plot(rlimit,zlimit,"ro")68 ## get contour for psi_ves boundary69 flpoints = get_fieldlines(cf,psi_ves,start_coord=(.05,.5),end_coord=(.05,-.5))70 r,z = flpoints[:,0],flpoints[:,1]71 z = np.array(list(z)+[-z[0]])72 z = z[::-1]73 r = np.array(list(r)+[r[0]])74 r = r[::-1]75 flpoints = np.vstack((z,r)).T76 fl_dist = get_fieldline_distance(flpoints)77 spl = UnivariateSpline(z,r,k=1,s=0)78 fl_spl = UnivariateSpline(fl_dist,z,k=1,s=0)79 uniform_s = np.linspace(fl_dist[0],fl_dist[-1],100)80 zves = fl_spl(uniform_s)81 rves = spl(zves)82# ax.plot(r,z,"yo")83# ax.plot(rves,zves,"go")84# plt.show()85 plt.close()86 lim_ves_pairs = [loc for pair in zip(rlimit,zlimit) for loc in pair]+[loc for pair in zip(rves,zves) for loc in pair]87 with open(fname,"w") as f:88 ## line 1 -- write grid information: cursign, nnr, nnz, nnv89 f.write(title+"".join("{:4d}".format(xi) for xi in [int(cursign),nnr,nnz,nnv]))90 ## line 2 -- write rbox,zbox,0,0,091 f.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [rbox,zbox,0,0,0]))92 ## line 3 -- write 0,0,0,psi_lim,093 f.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [0,0,0,psi_lim,0]))94 ## line 4 -- write total toroidal current,0,0,0,095 f.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [tot_cur,0,0,0,0]))96 ## line 5 -- write 0,0,0,0,097 f.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [0,0,0,0,0]))98 ## line 6 -- write list of toroidal flux for each flux surface (zeros)99 f.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(blank)))100 ## line 7 -- write list of pressure for each flux surface (zeros)101 f.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(blank)))102 ## line 8 -- write list of (RBphi)' for each flux surface (zeros)103 f.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(blank)))104 ## line 9 -- write list of P' for each flux surface (zeros)105 f.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(blank)))106 ## line 10 -- write flattened list of psi values on whole grid (NOT ZERO)107 f.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(psi.flatten())))108 ## line 11 -- write list of q for each flux surface (zeros)109 f.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(blank)))110 ## line 12 -- write number of coordinate pairs for limit surface and vessel surface111 f.write("\n"+"".join("{0:5d}{1:5d}".format(limit_pairs,vessel_pairs)))112 ## line 13 -- write list of R,Z pairs for limiter surface, then vessel surface113 f.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(lim_ves_pairs)))114def write_eqdsk_fromdict(eq_dict,fname):115 title = eq_dict["title"]116 cursign,nnr,nnz,nnv = eq_dict["cursign"], eq_dict["nnr"], eq_dict["nnz"], eq_dict["nnv"]117 rbox,zbox = eq_dict["rbox"],eq_dict["zbox"]118 psi_lim = eq_dict["psi_lim"]119 Ip = eq_dict["Ip"]120 p_flux = eq_dict["p_flux"]121 tor_flux = eq_dict["tor_flux"] 122 rbphi_flux = eq_dict["rbphi_flux"]123 pprime_flux = eq_dict["pprime_flux"]124 psi = eq_dict["psi"]125 q_flux = eq_dict["q_flux"]126 nlim_pairs = eq_dict["nlim_pairs"]127 nves_pairs = eq_dict["nves_pairs"]128 lim_pairs = eq_dict["lim_pairs"]129 ves_pairs = eq_dict["ves_pairs"]130 lim_ves_pairs = [loc for pair in lim_pairs for loc in pair] + [loc for pair in ves_pairs for loc in pair]131 with open(fname,"w") as fh:132 ## line 1 -- write grid information: cursign, nnr, nnz, nnv133 fh.write(title+"".join("{:4d}".format(xi) for xi in [int(cursign),nnr,nnz,nnv]))134 ## line 2 -- write rbox,zbox,0,0,0135 fh.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [rbox,zbox,0,0,0]))136 ## line 3 -- write 0,0,0,psi_lim,0137 fh.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [0,0,0,psi_lim,0]))138 ## line 4 -- write total toroidal current,0,0,0,0139 fh.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [Ip,0,0,0,0]))140 ## line 5 -- write 0,0,0,0,0141 fh.write("\n"+"".join("{: 16.9E}".format(xi) for xi in [0,0,0,0,0]))142 ## line 6 -- write list of toroidal flux for each flux surface (zeros)143 fh.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(tor_flux)))144 ## line 7 -- write list of pressure for each flux surface (zeros)145 fh.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(p_flux)))146 ## line 8 -- write list of (RBphi)' for each flux surface (zeros)147 fh.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(rbphi_flux)))148 ## line 9 -- write list of P' for each flux surface (zeros)149 fh.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(pprime_flux)))150 ## line 10 -- write flattened list of psi values on whole grid (NOT ZERO)151 fh.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(psi.flatten())))152 ## line 11 -- write list of q for each flux surface (zeros)153 fh.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(q_flux)))154 ## line 12 -- write number of coordinate pairs for limit surface and vessel surface155 fh.write("\n"+"".join("{0:5d}{1:5d}".format(nlim_pairs,nves_pairs)))156 ## line 13 -- write list of R,Z pairs for limiter surface, then vessel surface157 fh.write("\n"+"".join("{: 16.9E}\n".format(xi) if np.mod(i+1,5)==0 else "{: 16.9E}".format(xi) for i,xi in enumerate(lim_ves_pairs)))158def read_eqdsk(filename):159 """160 line 1 -- read grid information: title cursign, nnr, nnz, nnv161 line 2 -- read rbox,zbox,0,0,0162 line 3 -- read 0,0,0,psi_lim,0163 line 4 -- read total toroidal current,0,0,0,0164 line 5 -- read 0,0,0,0,0165 line 6 -- read list of toroidal flux for each flux surface (zeros)166 line 7 -- read list of pressure for each flux surface (zeros)167 line 8 -- read list of (RBphi)' for each flux surface (zeros)168 line 9 -- read list of P' for each flux surface (zeros)169 line 10 -- read flattened list of psi values on whole grid (NOT ZERO)170 line 11 -- read list of q for each flux surface (zeros)171 line 12 -- read number of coordinate pairs for limit surface and vessel surface172 line 13 -- read list of R,Z pairs for limiter surface, then vessel surface173 """174 eq_dict = {}175 with open(filename,"r") as f:176 lines = f.readlines()177 line1 = lines[0]178 eq_dict["title"] = line1[0:48]179 line1rem = line1[48:]180 eq_dict["cursign"] = int(line1rem.split()[-4])181 eq_dict["nnr"] = int(line1rem.split()[-3])182 eq_dict["nnz"] = int(line1rem.split()[-2])183 eq_dict["nnv"] = int(line1rem.split()[-1])184 line2 = lines[1].split()185 eq_dict["rbox"] = float(line2[-5])186 eq_dict["zbox"] = float(line2[-4])187 line3 = lines[2].split()188 eq_dict["psi_lim"] = float(line3[-2])189 line4 = lines[3].split()190 eq_dict["Ip"] = float(line4[-5])191 line5 = lines[4].split()192 fs_lines = int(np.ceil(eq_dict["nnv"]/5.0))193 head = [line.strip().split() for line in lines[5:5+fs_lines]]194 tor_flux = np.array([float(num) for line in head for num in line])195 eq_dict["tor_flux"] = tor_flux196 head = [line.strip().split() for line in lines[5+fs_lines:5+2*fs_lines]]197 p_flux = np.array([float(num) for line in head for num in line])198 eq_dict["p_flux"] = p_flux199 head = [line.strip().split() for line in lines[5+2*fs_lines:5+3*fs_lines]]200 rbphi_flux = np.array([float(num) for line in head for num in line])201 eq_dict["rbphi_flux"] = rbphi_flux202 head = [line.strip().split() for line in lines[5+3*fs_lines:5+4*fs_lines]]203 pprime_flux = np.array([float(num) for line in head for num in line])204 eq_dict["pprime_flux"] = pprime_flux205 # Read psi on whole grid, nnr x nnz206 nnr,nnz = eq_dict["nnr"],eq_dict["nnz"]207 rz_pts = nnr*nnz208 l0 = 5+4*fs_lines209 psi_lines = int(np.ceil(rz_pts/5.0))210 head = [line.strip().split() for line in lines[l0:l0+psi_lines]]211 psi = np.array([float(num) for line in head for num in line])212 eq_dict["psi"] = psi.reshape((nnz,nnr))213 rbox,zbox = eq_dict["rbox"],eq_dict["zbox"]214 R,Z = np.meshgrid(np.linspace(0,rbox,nnr),np.linspace(-zbox/2,zbox/2,nnz))215 eq_dict["R"] = R216 eq_dict["Z"] = Z217 head = [line.strip().split() for line in lines[l0+psi_lines:l0+psi_lines+fs_lines]]218 q_flux = np.array([float(num) for line in head for num in line])219 eq_dict["q_flux"] = q_flux220 nlim_pairs, nves_pairs = [int(x) for x in lines[l0+psi_lines+fs_lines].strip().split()]221 eq_dict["nlim_pairs"] = nlim_pairs222 eq_dict["nves_pairs"] = nves_pairs223 pair_lines = int(np.ceil((nlim_pairs + nves_pairs)*2.0/5.0))224 rest = [line.rstrip() for line in lines[l0+psi_lines+fs_lines+1:]]225 rest = [line[i:i+16] for line in rest for i in range(0,len(line),16)]226 pairs = np.array([float(num.strip()) for num in rest])227 lim_pairs = np.array(list(zip(pairs[0:2*nlim_pairs:2],pairs[1:2*nlim_pairs:2])))228 ves_pairs = np.array(list(zip(pairs[2*nlim_pairs::2],pairs[2*nlim_pairs+1::2])))229 eq_dict["lim_pairs"] = lim_pairs230 eq_dict["ves_pairs"] = ves_pairs...
399.evaluate-division.py
Source:399.evaluate-division.py
1#2# @lc app=leetcode id=399 lang=python33#4# [399] Evaluate Division5#6# @lc code=start7class Solution:8 def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:9 from collections import defaultdict10 eq_dict = defaultdict(dict)11 for (a, b), val in zip(equations, values):12 eq_dict[a][b] = val13 eq_dict[b][a] = 1 / val14 for (a, b), val in zip(equations, values):15 for c in eq_dict[a]:16 eq_dict[b][c] = eq_dict[a][c] / eq_dict[a][b]17 eq_dict[c][b] = 1 / eq_dict[b][c]18 for c in eq_dict[b]:19 eq_dict[a][c] = eq_dict[b][c] / eq_dict[b][a]20 eq_dict[c][a] = 1 / eq_dict[a][c]21 res = []22 for a, b in queries:23 curr_res = -124 for c in eq_dict:25 if a in eq_dict and b in eq_dict[a]:26 curr_res = eq_dict[a][b]27 break28 res.append(curr_res)29 return res30# directed graph: Building graph: O(E) and O(E), each query: O(N) and O(1)31class Solution(object):32 def calcEquation(self, equations, values, queries):33 graph = {}34 def build_graph(equations, values):35 def add_edge(f, t, value):36 if f in graph:37 graph[f].append((t, value))38 else:39 graph[f] = [(t, value)]40 for vertices, value in zip(equations, values):41 f, t = vertices42 add_edge(f, t, value)43 add_edge(t, f, 1/value)44 def find_path(query):45 b, e = query46 if b not in graph or e not in graph:47 return -1.048 q = collections.deque([(b, 1.0)])49 visited = set()50 while q:51 front, cur_product = q.popleft()52 if front == e:53 return cur_product54 visited.add(front)55 for neighbor, value in graph[front]:56 if neighbor not in visited:57 q.append((neighbor, cur_product*value))58 return -1.059 build_graph(equations, values)60 return [find_path(q) for q in queries]...
eq_explore _data.py
Source:eq_explore _data.py
1import json2from plotly.graph_objs import Scattergeo, Layout3from plotly import offline4# Explore the structure of the data.5filename = 'data/1.0_month.geojson.json'6with open(filename,encoding="utf8") as f:7 all_eq_data = json.load(f)8 readable_file = 'data/readable_eq_data.json'9with open(readable_file, 'w') as f:10 json.dump(all_eq_data, f, indent=4)11all_eq_dicts = all_eq_data['features']12title = all_eq_data['metadata']['title']13mags = [eq_dict['properties']['mag'] for eq_dict in all_eq_dicts]14lons = [eq_dict['geometry']['coordinates'][0] for eq_dict in all_eq_dicts]15lats = [eq_dict['geometry']['coordinates'][1] for eq_dict in all_eq_dicts]16hover_texts = [eq_dict['properties']['title'] for eq_dict in all_eq_dicts]17# Map the earthquakes.18data = [{19'type': 'scattergeo',20'lon': lons,21'lat': lats,22'text': hover_texts,23'marker': {24 'size': [5*mag for mag in mags],25 'color': mags,26 'colorscale': 'Viridis',27 'reversescale': True,28 'colorbar': {'title': 'Magnitude'},29 },30}]31my_layout = Layout(title=f'{title}')32fig = {'data': data, 'layout': my_layout}...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!