Identity Map

对象缓存机制

 

概念<o:p></o:p>

通过在map中保存所有的加载对象,确保对象只加载一次,每次查找对象都先去map中查找是否有这个对象,如果有就返回,没有才去加载<o:p></o:p>

场景<o:p></o:p>

1、管理从数据库加载的对象,使之持久对象在内存中始终唯一<o:p></o:p>

2、作为从数据库加载对象的缓存器,可以避免每次读数据时候都要从数据库加载<o:p></o:p>

应用<o:p></o:p>

单数据库简单用法:对每个表都有一个对应的map,当需要从数据库中加载一个对象的时候,你首先核实一下map,如果map中存在一个和你所需要加载的对象相等的一个对象,直接返回这个对象,如果没有,查找数据库,并且把加载出来的对象放到map中。<o:p></o:p>

注意点<o:p></o:p>

1、关键字的选择:以表名作为map的关键字,以主键作为map中各个对象的关键字<o:p></o:p>

2Explicit or GenericGeneric是对每类对象都采用一个方法,比如find("Person", 1),其中一个输入参数制定是什么类型的对象,好处在新增加一个map不需要重新些一个方法。Explicit是对每类对象分别采用不同的方法,比如:findPerson(1),好处比较直观,如果通过泛型来做的,也可以做到新增一个map不用重新一个方法。<o:p></o:p>

3map的数量:每类对象对应一个map,如果不同类的每个对象都有一种标识能区别的,可以用次方法,有利于管理map,而且增加一类对象的时候也不需要在家map;整个session对应一个map,比较符合数据库的设计,每个map用表名作为key,比较清晰,但是比较难处理的是继承树的处理。<o:p></o:p>

4、存放位置:如果存放在processContext,必须关注的是必须确保不同session只能得到他自己的对象。还有就是对map要进行事务性的保护,其中涉及到两个问题,第一个就是尽管你是用关系型数据库来保存数据,但是你必须把加载的数据作为对象放在事务性缓存中,第二个是那些只读对象,因为不需要进行修改,所以可以在整个processContext中都可以使用,有种方法是只读对象的map放在processContext中,可修改对象的map放在session中。
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from SimPEG import maps from SimPEG.potential_fields import magnetics from discretize import TensorMesh import os print("=== Magnetic Forward Modeling for Coal Fire Detection ===") output_dir = "Magnetic_Results" os.makedirs(output_dir, exist_ok=True) print(f"Results will be saved to: {output_dir}") def create_model1_horizontal_slab(): model = np.zeros(mesh.nC) centers = mesh.cell_centers indices = ( (centers[:, 0] >= -80) & (centers[:, 0] <= 80) & (centers[:, 2] >= -60) & (centers[:, 2] <= -40) & (centers[:, 1] >= -5) & (centers[:, 1] <= 5) ) model[indices] = 0.08 return model, "01_Horizontal_Slab" def create_model2_dipping_slab(): model = np.zeros(mesh.nC) centers = mesh.cell_centers angle = np.radians(30) rotated_x = centers[:, 0] * np.cos(angle) - centers[:, 2] * np.sin(angle) rotated_z = centers[:, 0] * np.sin(angle) + centers[:, 2] * np.cos(angle) indices = ( (rotated_x >= -60) & (rotated_x <= 60) & (rotated_z >= -10) & (rotated_z <= 10) & (centers[:, 1] >= -5) & (centers[:, 1] <= 5) ) model[indices] = 0.07 return model, "02_Dipping_Slab" def create_model3_rectangular_prism(): model = np.zeros(mesh.nC) centers = mesh.cell_centers indices = ( (centers[:, 0] >= -40) & (centers[:, 0] <= 40) & (centers[:, 2] >= -100) & (centers[:, 2] <= -60) & (centers[:, 1] >= -5) & (centers[:, 1] <= 5) ) model[indices] = 0.06 return model, "03_Rectangular_Prism" def create_model4_two_anomalies(): model = np.zeros(mesh.nC) centers = mesh.cell_centers indices1 = ( (centers[:, 0] >= -100) & (centers[:, 0] <= -50) & (centers[:, 2] >= -50) & (centers[:, 2] <= -30) & (centers[:, 1] >= -5) & (centers[:, 1] <= 5) ) indices2 = ( (centers[:, 0] >= 30) & (centers[:, 0] <= 90) & (centers[:, 2] >= -90) & (centers[:, 2] <= -50) & (centers[:, 1] >= -5) & (centers[:, 1] <= 5) ) model[indices1] = 0.09 model[indices2] = 0.05 return model, "04_Two_Anomalies" def create_model5_complex(): model = np.zeros(mesh.nC) centers = mesh.cell_centers indices1 = ( (centers[:, 0] >= -120) & (centers[:, 0] <= -60) & (centers[:, 2] >= -40) & (centers[:, 2] <= -20) & (centers[:, 1] >= -5) & (centers[:, 1] <= 5) ) angle = np.radians(45) rotated_x = (centers[:, 0] - 50) * np.cos(angle) - (centers[:, 2] + 70) * np.sin(angle) rotated_z = (centers[:, 0] - 50) * np.sin(angle) + (centers[:, 2] + 70) * np.cos(angle) indices2 = ( (rotated_x >= -30) & (rotated_x <= 30) & (rotated_z >= -8) & (rotated_z <= 8) & (centers[:, 1] >= -5) & (centers[:, 1] <= 5) ) model[indices1] = 0.08 model[indices2] = 0.065 return model, "05_Complex_Model" print("Initializing...") mesh = TensorMesh([ np.ones(100) * 10, np.ones(1) * 10, np.ones(80) * 5 ], x0=['C', 'C', 0]) print(f"Mesh created: {mesh.nC} cells") x_locations = np.linspace(-150, 150, 61) y_locations = np.zeros_like(x_locations) z_locations = np.ones_like(x_locations) * 10 receiver_locations = np.c_[x_locations, y_locations, z_locations] H0 = 50000 incl = 50 decl = -5 receivers = magnetics.receivers.Point(receiver_locations, components="tmi") source_field = magnetics.sources.UniformBackgroundField( receiver_list=[receivers], amplitude=H0, inclination=incl, declination=decl ) survey = magnetics.survey.Survey(source_field) print("Survey system setup completed: 61 stations") all_models = [ create_model1_horizontal_slab, create_model2_dipping_slab, create_model3_rectangular_prism, create_model4_two_anomalies, create_model5_complex ] print("\nStarting forward modeling...") results = {} for i, model_func in enumerate(all_models): print(f"Progress: {i+1}/{len(all_models)} - Calculating model {i+1}...") model, model_name = model_func() simulation = magnetics.simulation.Simulation3DIntegral( survey=survey, mesh=mesh, modelType='scalar', chiMap=maps.IdentityMap(nP=mesh.nC) ) data = simulation.dpred(model) results[model_name] = { 'model': model, 'data': data, 'receiver_locations': receiver_locations } fig, axes = plt.subplots(2, 2, figsize=(15, 12)) fig.suptitle(f'Magnetic Modeling - {model_name}', fontsize=16) model_2d = model.reshape(mesh.shape[0], mesh.shape[1], mesh.shape[2])[:, 0, :] x_centers = mesh.cell_centers_x z_centers = mesh.cell_centers_z X, Z = np.meshgrid(x_centers, z_centers, indexing='ij') im1 = axes[0,0].pcolormesh(X, Z, model_2d.T, cmap='jet', shading='auto') axes[0,0].set_xlabel('Distance (m)') axes[0,0].set_ylabel('Depth (m)') axes[0,0].set_title('Underground Model') axes[0,0].set_aspect('equal') plt.colorbar(im1, ax=axes[0,0], label='Susceptibility') axes[0,0].axhline(y=0, color='k', linestyle='-', linewidth=1) axes[0,1].plot(receiver_locations[:,0], data, 'b-', linewidth=2, marker='o', markersize=3) axes[0,1].set_xlabel('Station Position (m)') axes[0,1].set_ylabel('Magnetic Anomaly (nT)') axes[0,1].set_title('Surface Magnetic Data') axes[0,1].grid(True, alpha=0.3) axes[0,1].fill_between(receiver_locations[:,0], data, alpha=0.3, color='blue') ax3d = axes[1,0] centers = mesh.cell_centers mask = model > 0.01 if np.any(mask): scatter = ax3d.scatter(centers[mask, 0], centers[mask, 1], centers[mask, 2], c=model[mask], cmap='jet', s=10) ax3d.set_xlabel('X (m)') ax3d.set_ylabel('Y (m)') ax3d.set_zlabel('Depth (m)') ax3d.set_title('3D Model View') axes[1,1].axis('off') info_text = f"""Model Info: Name: {model_name} Data Range: {np.min(data):.1f} ~ {np.max(data):.1f} nT Peak Anomaly: {np.max(np.abs(data)):.1f} nT Stations: {len(data)} Anomaly Cells: {np.sum(model > 0.01)} Max Susceptibility: {np.max(model):.3f} SI""" axes[1,1].text(0.1, 0.9, info_text, fontsize=12, verticalalignment='top', linespacing=1.5) plt.tight_layout() plt.savefig(f'{output_dir}/{model_name}.png', dpi=300, bbox_inches='tight') plt.close(fig) print(f" Saved: {model_name}.png") print("\nSaving data files...") np.save(f'{output_dir}/all_models_data.npy', results) print("Generating report...") with open(f'{output_dir}/data_report.txt', 'w') as f: f.write("Magnetic Forward Modeling Dataset Summary\n") f.write("="*50 + "\n\n") f.write(f"Generated: {np.datetime64('now')}\n") f.write(f"Total Models: {len(all_models)}\n") f.write(f"Stations: {len(receiver_locations)}\n") f.write(f"Mesh Size: {mesh.nC} cells\n\n") f.write("Magnetic Anomaly Statistics:\n") f.write("-"*30 + "\n") for name in results: data = results[name]['data'] f.write(f"{name}: {np.min(data):7.1f} ~ {np.max(data):7.1f} nT (Peak: {np.max(np.abs(data)):7.1f} nT)\n") print("="*50) print("🎉 Project Completed!") print(f"✅ Generated {len(all_models)} typical fire zone models") print(f"✅ All results saved to '{output_dir}' folder") print(f"✅ Data file: all_models_data.npy") print(f"✅ Report: data_report.txt") print("\nYou now have a complete dataset for deep learning!") print("- Underground models are your [LABELS]") print("- Surface magnetic data are your [FEATURES]")
最新发布
10-07
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值