def run_permanent_magnets(preProcData, folder_path):
    print("Running permanent magnetic field solution")

    #===============================================================================
    # Pre-processor
    mesh_data = preProcData.MeshData
    all_elem_nodes = mesh_data.ElemNodes
    elem_tags = mesh_data.ElemTags
    regions_material = preProcData.RegionMaterial
    materials_lib = get_materials_lib()
    elem_type = mesh_data.ElemType

    #==============================================================================
    # Get the Hc value from materials lib
    gauss_points_coordinates, phys_region_list, points_ID_list = Get_Gauss_points_list(
        preProcData, True, folder_path)
    global_Hc_list = list()
    for each_point_phys_region in phys_region_list:
        for each_region in regions_material:
            if each_region.RegionNumber == each_point_phys_region:
                matrial_name = each_region.MaterialName
        Hc = materials_lib[matrial_name].Hc
        global_Hc_list.append(Hc)

#==============================================================================
# Folder results path
    file_names = File_names()
    results_folder = file_names.get_results_folder_name()
    folder_path = os.path.join(folder_path, results_folder)

    #==============================================================================
    # Write file with the results
    file_names = File_names()
    h_field_results_file_name = file_names.get_H_results_file_name()
    full_path = os.path.join(folder_path, h_field_results_file_name)
    write_numeric_file_numpy(full_path, global_Hc_list)

    #==============================================================================
    # GMSH post processing
    file_names = File_names()
    Gmsh_file_name = file_names.get_H_Gmsh_pos_proc_file_name()
    path = os.path.join(folder_path, Gmsh_file_name)

    Create_Vector_field(gauss_points_coordinates, global_Hc_list, path,
                        "Hc source")
def write_files(faces_list,results_path,faces_ID,complete_flux):
	#flux
	file_names=File_names()
	flux_results_file_name=file_names.flux_results_file_name()
	full_path=os.path.join(results_path,flux_results_file_name)
	write_numeric_file_numpy(full_path,complete_flux)
	
	#faces from to
	number_faces=len(faces_list)
	from_to=np.zeros((number_faces,2))
	counter=0
	for each_face in faces_list:
		from_to[counter,0]=each_face.elem_1
		from_to[counter,1]=each_face.elem_2
		counter+=1
	from_to_file_name=file_names.faces_from_to_file_name()
	full_path=os.path.join(results_path,from_to_file_name)
	write_numeric_file_numpy(full_path,from_to)
	
	#faces ID
	faces_ID_file_name=file_names.get_faces_ID_file_name()
	full_path=os.path.join(results_path,faces_ID_file_name)
	write_numeric_data_file(full_path,faces_ID,"faces_ID",True)
def write_files(faces_list, results_path, faces_ID, complete_flux):
    #flux
    file_names = File_names()
    flux_results_file_name = file_names.flux_results_file_name()
    full_path = os.path.join(results_path, flux_results_file_name)
    write_numeric_file_numpy(full_path, complete_flux)

    #faces from to
    number_faces = len(faces_list)
    from_to = np.zeros((number_faces, 2))
    counter = 0
    for each_face in faces_list:
        from_to[counter, 0] = each_face.elem_1
        from_to[counter, 1] = each_face.elem_2
        counter += 1
    from_to_file_name = file_names.faces_from_to_file_name()
    full_path = os.path.join(results_path, from_to_file_name)
    write_numeric_file_numpy(full_path, from_to)

    #faces ID
    faces_ID_file_name = file_names.get_faces_ID_file_name()
    full_path = os.path.join(results_path, faces_ID_file_name)
    write_numeric_data_file(full_path, faces_ID, "faces_ID", True)
def integration_process(folder_path,preProcData):
	file_names=File_names()
	results_folder=file_names.get_results_folder_name()
	results_path=os.path.join(folder_path,results_folder)

#	Source field
	mu0=4.0*math.pi*math.pow(10.0,-7.0)
	run_surface_integral=True
	run_biot_savart=True
	run_VS=False
	perf_mag_surf=177
	one_layer_ID=175
#%% Instances and geral definitions
	global_variables=GlobalVariables()
	error=Errors()
	operations=Operations()
	materials_lib=get_materials_lib()
	vacuum=Vacuum()
	get_gauss_points_class=GaussPoints()
	shape_functions=ShapeFuncions()
	operations=Operations()

	str_noflux_face=global_variables.str_noflux_face
	results_folder=file_names.get_results_folder_name()

	face=Face()
	#------------------------------------------------------------------------------
	# Setup
	regions_material=preProcData.RegionMaterial
	regions_excitation=preProcData.RegionExcitation
	boundary=preProcData.BC
	external_reluctances=preProcData.ExternalReluctances
	coupling=preProcData.CoupNet


	#------------------------------------------------------------------------------
	# Mesh
	mesh_data=preProcData.MeshData
	all_elem_nodes_3D= mesh_data.ElemNodes
	nodes_coordenates=mesh_data.NodesCoordenates
	elem_tags=mesh_data.ElemTags
	elem_type=mesh_data.ElemType

	#%% Get 2D and 3D elements, with their materials name
	elem_2D_ID=list()
	elem_type_3D=list()
	elem_nodes_3D=list()
	elem_tags_3D=list()
	region_ID_list_3D=list()
	number_elements_2D=0
	nodes_phys_surf=list()

	for counter,each_elem in enumerate(all_elem_nodes_3D):
		this_elem_type=elem_type[counter]
		if this_elem_type<4:
			elem_2D_ID.append(counter)
			number_elements_2D+=1
			if elem_tags[counter][0]==perf_mag_surf:
				for each in all_elem_nodes_3D[counter]:
					if each not in nodes_phys_surf:
						nodes_phys_surf.append(each)
		else:
			elem_nodes_3D.append(each_elem)
			elem_type_3D.append(elem_type[counter])
			elem_tags_3D.append(elem_tags[counter])

			find=False
			for each_region in regions_material:
				if each_region.RegionNumber==elem_tags[counter][0]:
					region_ID_list_3D.append(each_region.MaterialName)
					find=True
			if not find:
			   error.physical_surface_not_defined(str(each_region.RegionNumber),elem_tags[counter][0])

	number_elements=len(elem_nodes_3D) #only 3D elements
	number_nodes=len(nodes_coordenates)
	faces_ID=list()
	faces_list=list()
#	nodes_phys_surf=set(nodes_phys_surf)
	plot_field=list()
	plot_shape_functions=list()
	plot_test_coord=list()



	#%%Get source field
	field_solution=list()
	run_permanent_magnets=False

#	Run Permanent Magnets
	for each_region in regions_material:
		for each in materials_lib[each_region.MaterialName].Hc:
			if each !=0.0:
				permanent_magnets.run_permanent_magnets(preProcData,folder_path)
				run_permanent_magnets=True
				break

	#Read the fields
	if run_biot_savart or run_permanent_magnets:

		results_folder=file_names.get_results_folder_name()
		folder_name=os.path.join(folder_path,results_folder)

		#Gauss points IDs
		this_file_name=file_names.get_Gauss_points_ID_file_name()
		full_path=os.path.join(folder_name,this_file_name)
		points_IDs = np.genfromtxt(full_path,delimiter=' ',dtype='int', usecols=(1,2,3,4))
		points_ID_elem_all = np.genfromtxt(full_path,delimiter=' ',dtype='int', usecols=(0))
		points_ID_elem=points_ID_elem_all-number_elements_2D
		points_ID_elem=points_ID_elem.tolist()
		points_ID_elem_all=points_ID_elem_all.tolist()


#		Gauss points coordinates
		this_file_name=file_names.get_Gauss_points_coordinates_file_name()
		full_path=os.path.join(folder_name,this_file_name)
		coordinates = np.genfromtxt(full_path,delimiter=' ',dtype='double')


#		Fields
		this_file_name=file_names.get_Gauss_points_H_field_file_name()
#		this_file_name="H_source_FFEM.txt"

		full_path=os.path.join(folder_name,this_file_name)
		fields = np.genfromtxt(full_path,delimiter=' ',dtype='double')
		for elem_counter in range(0,number_elements):
			this_elem_type=elem_type_3D[elem_counter]
			gauss_points=get_gauss_points_class.get_gauss_points(this_elem_type)
			number_integ_points=len(get_gauss_points_class.get_gauss_points(this_elem_type))
			this_points_field=list()
			if elem_counter in points_ID_elem:

				this_elem=points_ID_elem.index(elem_counter)
				for k in points_IDs[this_elem].tolist():
					Hxy=np.zeros((3,1))
					Hxy[0,0]=fields[k,0]
					Hxy[1,0]=fields[k,1]
					Hxy[2,0]=fields[k,2]


					this_points_field.append(Hxy)

			else:
				for k in xrange(number_integ_points):
					Hxy=np.zeros((3,1))
					this_points_field.append(Hxy)
			field_solution.append(this_points_field)


	run_external_circuit=False
	if len(coupling)>0:
		run_external_circuit=True


#%%Creates the face list
	print_message("Creating faces list")
	for elem_counter in range(0,number_elements):
		number_local_faces=shape_functions.get_number_faces(this_elem_type)
		this_elem_type=elem_type_3D[elem_counter]
		this_element_nodes=elem_nodes_3D[elem_counter]
		faces_nodes_ID=shape_functions.get_nodes_ID_2_face(this_elem_type)
		number_faces,nodes_per_face=faces_nodes_ID.shape
		local_faces_ID=list()
		for local_face_counter in range(0,number_faces):
			nodes_list=list()
			for node_counter in range(nodes_per_face):
				node_ID=faces_nodes_ID[local_face_counter,node_counter]
				nodes_list.append(this_element_nodes[node_ID])
			local_faces_ID.append(face.add_to_list(nodes_list,elem_counter,faces_list))
		faces_ID.append(local_faces_ID)
	print_message("Creating faces list - Done")


#%%Integration
	print_message("Integration process")

	num_meshed_rel=len(faces_list)
	num_non_meshed_rel=len(external_reluctances)
	num_total_rel=num_meshed_rel+num_non_meshed_rel

#sparse matrix
	cols_rel_sparse=list()
	rows_rel_sparse=list()

	counter_elem_suf=0

#reluctance matrix
	diagonal=list()
	for each_element_faces in faces_ID:
		numbre_faces_this_element=len(each_element_faces)
		for face_counter_1 in xrange(numbre_faces_this_element):
			pos_1=each_element_faces[face_counter_1]
			for face_counter_2 in xrange(numbre_faces_this_element):
				pos_2=each_element_faces[face_counter_2]
				if pos_1==pos_2:
					if pos_1 not in diagonal:
						rows_rel_sparse.append(pos_1)
						cols_rel_sparse.append(pos_2)
						diagonal.append(pos_1)
				else:
					rows_rel_sparse.append(pos_1)
					cols_rel_sparse.append(pos_2)

	data_rel_sparse=np.zeros(len(rows_rel_sparse))
	faces_rel_spare=csr_matrix((data_rel_sparse, (rows_rel_sparse, cols_rel_sparse)), shape=(num_total_rel, num_total_rel))

#fmm matrix
	cols_fmm_sparse=np.zeros(num_meshed_rel)
	rows_fmm_sparse=xrange(0,num_meshed_rel)
	data_fmm_sparse=np.zeros(num_meshed_rel)
	fmm_sparse=csr_matrix((data_fmm_sparse, (rows_fmm_sparse, cols_fmm_sparse)), shape=(num_total_rel,1))

#source_flux matrix
	cols_source_flux_sparse=np.zeros(num_meshed_rel)
	rows_source_flux_sparse=xrange(0,num_meshed_rel)
	data_source_flux_sparse=np.zeros(num_meshed_rel)
	source_flux_sparse=csr_matrix((data_source_flux_sparse, (rows_source_flux_sparse, cols_source_flux_sparse)), shape=(num_total_rel,1))
#grad_phi matrix
#	cols_grad_phi_sparse=np.zeros(num_meshed_rel)
#	rows_grad_phi_sparse=xrange(0,num_meshed_rel)
#	data_grad_phi_sparse=np.zeros(num_meshed_rel)
#	grad_phi_sparse=csr_matrix((data_grad_phi_sparse, (rows_grad_phi_sparse, cols_grad_phi_sparse)), shape=(num_total_rel,1))

	this_elem_type=""
	for elem_counter in xrange(number_elements):
		this_elem_type_changed=elem_type_3D[elem_counter]
		if this_elem_type!=this_elem_type_changed:
			this_elem_type=this_elem_type_changed
			gauss_points=get_gauss_points_class.get_gauss_points(this_elem_type)
			number_local_faces=shape_functions.get_number_faces(this_elem_type)
			number_integ_points=len(get_gauss_points_class.get_gauss_points(this_elem_type))
			wtri=get_gauss_points_class.get_integration_weight(this_elem_type)

		faces_ID_Elem=faces_ID[elem_counter]
		this_element_nodes=elem_nodes_3D[elem_counter]
		mur_r=materials_lib[region_ID_list_3D[elem_counter]].Permeability
		mu_elem=vacuum.mu0*mur_r

		k_sf=1.0
		if run_VS:
			if mur_r>1.0:
				k_sf=-1.0*mu0*((1.0/mu_elem)-(1.0/mu0))
			else:
				k_sf=0


# Get W at reference element
		w_local_this_element=list() #[gauss point][face]
		for each_integ_point in xrange(number_integ_points):

#u,v,w coordinates
			u=gauss_points[each_integ_point,0]
			v=gauss_points[each_integ_point,1]
			w=gauss_points[each_integ_point,2]

# Shape functions @ reference element
			w_local_this_point=shape_functions.get_facet_shape_function(this_elem_type,u,v,w)
			w_local_this_element.append(w_local_this_point)

# Shape functions @ real element for each face
		w_real_all_points=list() # w_real_lista[0] contains  the shape function of all points for face 0

#   Face 0...Fn
#P0  W
#Pn

		for face_counter in xrange(number_local_faces):
			w_real_this_point=list()
			for point_counter in  range(0,number_integ_points):
				w_local=w_local_this_element[point_counter][face_counter]
				w_real=operations.convert_local_real_Piola(this_elem_type,w_local[0,0],w_local[0,1],w_local[0,2],this_element_nodes,nodes_coordenates)
				w_real_this_point.append(w_real)
			w_real_all_points.append(w_real_this_point)

# Source fields
		elem_ID_all=elem_counter+number_elements_2D
		for local_face_counter in xrange(number_local_faces):

			w_1=copy.deepcopy(w_real_all_points[local_face_counter])
			face_ID_1=faces_ID_Elem[local_face_counter]

			if faces_list[face_ID_1].elem_2==elem_counter:
				for each in w_1:
					each=matrix_aux.invert_w(each)

# mmf source integration process

#			if (52 in faces_list[face_ID_1].nodes_list) and (118 in faces_list[face_ID_1].nodes_list) and (384 in faces_list[face_ID_1].nodes_list):
#				faces_list[face_ID_1].print_face()
#				run_this_face=True


			counter_nodes=0
			for each in faces_list[face_ID_1].nodes_list:
				if  each in nodes_phys_surf:
					counter_nodes=counter_nodes+1
#					run_this_face=False
			run_this_face=False

			if  elem_counter in points_ID_elem:
				run_this_face=True


#			if (50 in faces_list[face_ID_1].nodes_list) and (120 in faces_list[face_ID_1].nodes_list):
#				run_this_face=True
#				faces_list[face_ID_1].print_face()
##					print(faces_list[face_ID_1].nodes_list)

			if run_this_face:

#Gets the ID of the element
				this_3D_ID=points_ID_elem_all.index(elem_ID_all)
#				print(this_3D_ID)
				this_face_nodes=faces_list[face_ID_1].nodes_list
#				faces_list[face_ID_1].print_face()


				source=0
				for each_integ_point in xrange(number_integ_points):

#					this_Gauss_point_ID=points_IDs[this_3D_ID][each_integ_point]

#					if run_biot_savart or run_permanent_magnets:
					Hxy=np.zeros((3,1))
					this_gauss_point_ID=points_IDs[this_3D_ID][each_integ_point]
					Hxy[0,0]=fields[this_gauss_point_ID][0]
					Hxy[1,0]=fields[this_gauss_point_ID][1]
					Hxy[2,0]=fields[this_gauss_point_ID][2]


#						Hxy=field_solution[elem_counter][each_integ_point]*k_sf

					w_1_this_point=w_1[each_integ_point]
#u,v,p coordinates
					u=gauss_points[each_integ_point,0]
					v=gauss_points[each_integ_point,1]
					p=gauss_points[each_integ_point,2]
					w=w_1_this_point

# Normal vector
					node1=this_face_nodes[0]
					node2=this_face_nodes[1]
					node3=this_face_nodes[2]
					P_1=np.array([nodes_coordenates[node1][0],nodes_coordenates[node1][1],nodes_coordenates[node1][2]])
					P_2=np.array([nodes_coordenates[node2][0],nodes_coordenates[node2][1],nodes_coordenates[node2][2]])
					P_3=np.array([nodes_coordenates[node3][0],nodes_coordenates[node3][1],nodes_coordenates[node3][2]])
					A=P_2-P_1
					B=P_3-P_1
					AxB=np.cross(A,B)
					nor=linalg.norm(AxB)
					n=AxB/nor
					n=np.array([[n[0]],[n[1]],[n[2]]])
#Shape funtions
					vdotn=matrix_aux.dot_product(w,n)
					w_n=n*vdotn
					w_t=w-w_n
					w=-w_n
					plot_shape_functions.append(w)
					plot_test_coord.append(coordinates[this_gauss_point_ID])
#Source field
					vdotn=matrix_aux.dot_product(Hxy,n)
					Hxy_n=n*vdotn
					plot_field.append(Hxy)
# Jacobian
					jac=operations.get_jacobian(this_elem_type,this_element_nodes,nodes_coordenates,u,v,p)
					det_jac=np.linalg.det(jac)
					abs_det_jac=np.abs(det_jac)
#Integration
					source=source+wtri*abs_det_jac*matrix_aux.dot_product(w,Hxy)

				fmm_sparse[face_ID_1,0]=fmm_sparse[face_ID_1,0]+source

# Relutances integration process
			for local_face_counter_2 in xrange(number_local_faces):
				w_2=copy.deepcopy(w_real_all_points[local_face_counter_2])
				face_ID_2=faces_ID_Elem[local_face_counter_2]

				if faces_list[face_ID_2].elem_2==elem_counter:
					 for each in w_2:
						 each=matrix_aux.invert_w(each)

				wtot=0.0
				for each_integ_point in range(0,number_integ_points):
					 u=gauss_points[each_integ_point,0]
					 v=gauss_points[each_integ_point,1]
					 p=gauss_points[each_integ_point,2]

# Jacobian
					 jac=operations.get_jacobian(this_elem_type,this_element_nodes,nodes_coordenates,u,v,p)
					 det_jac=np.linalg.det(jac)
					 abs_det_jac=np.abs(det_jac)

# Reluctance
					 w_1_this_point=w_1[each_integ_point]
					 w_2_this_point=w_2[each_integ_point]
					 wtot=wtot+wtri*abs_det_jac*matrix_aux.dot_product(w_1_this_point,w_2_this_point)/mu_elem

				faces_rel_spare[face_ID_1,face_ID_2]+=wtot
	print_message("Integration process - Done")


#%% Connection between the physical line with the circuit node
	print_message("External faces")

	for counter,each_face in enumerate(faces_list):
		if each_face.elem_2==str_noflux_face:
			for each_face_con in elem_2D_ID:
				nodes_face_shared=all_elem_nodes_3D[each_face_con]
				phys_line=elem_tags[each_face_con][0]

#Coupling with external reluctances
				for each_coupling in coupling:
					if each_coupling.PhysLine==phys_line:

						bool_connect=True
						for each_node_this_face in each_face.nodes_list:
							if each_node_this_face not in nodes_face_shared:
								bool_connect=False

						if bool_connect:
# Redefine the face
							   new_face=Face(each_face.nodes_list,each_face.elem_1,each_coupling.Node+number_elements)
							   faces_list[counter]=new_face
							   each_coupling.Face_ID_List.append(counter)

#%% Insert the flux sources

	BC_nodes=list()
	if run_surface_integral:
		folder_name=os.path.join(folder_path,results_folder)
		full_path=os.path.join(folder_name,"flux_surface.txt")
		flux_data = np.genfromtxt(full_path,delimiter=' ',dtype='double')
		flux_source =flux_data[:,1]
		flux_source_elem_ID=flux_data[:,0]
		num_faces_surface_integral=len(flux_source_elem_ID)
#		external_node_surface_ID_counter=0

		for face_counter in xrange(num_faces_surface_integral):
			this_elem_face_ID=int(flux_source_elem_ID[face_counter])
			this_face_nodes_elem=set(all_elem_nodes_3D[this_elem_face_ID])

			for counter,each_face in enumerate(faces_list):
				this_face_nodes=set(each_face.nodes_list)
				if this_face_nodes_elem.issubset(this_face_nodes):
#					print this_elem_face_ID
#					external_node_surface_ID=len(coupling)+number_elements-1
#					BC_nodes.append(external_node_surface_ID)
#					external_node_surface_ID_counter+=1
					new_face=Face(each_face.nodes_list,each_face.elem_1,each_face.elem_2)
					faces_list[counter]=new_face
					source_flux_sparse[counter]=flux_source[face_counter]
					faces_rel_spare[counter,counter]=10000000000000000.0
					fmm_sparse[counter,0]=0.0
#					print each_face.elem_1
#					break

	BC_values=[0]*len(BC_nodes)


#%% Delete the faces without external connections
	faces_ID_deleted_list=list()
	faces_deleted_list=list()

#Delete from reluctances and fmm matrix
	counter=0
	for face_counter in  xrange(len(faces_list)):
		if faces_list[face_counter].elem_2==str_noflux_face:
			faces_ID_deleted_list.append(face_counter)

	faces_rel_spare=matrix_aux.delete_sparse_mask(faces_rel_spare,faces_ID_deleted_list,0)
	faces_rel_spare=matrix_aux.delete_sparse_mask(faces_rel_spare,faces_ID_deleted_list,1)
	fmm_sparse=matrix_aux.delete_sparse_mask(fmm_sparse,faces_ID_deleted_list,0)
	source_flux_sparse=matrix_aux.delete_sparse_mask(source_flux_sparse,faces_ID_deleted_list,0)

##Delete from faces_list
	counter=0
	for each in faces_ID_deleted_list:
		face_ID=each+counter
		this_face=faces_list[face_ID]
		faces_list.remove(this_face)
		faces_deleted_list.append(this_face)
		counter-=1

#%% Add the external circuit reluctances
	number_deleted=len(faces_deleted_list)
	for counter in xrange(num_non_meshed_rel):

#reluctance value
		material=external_reluctances[counter].Material
		mur=materials_lib[material].Permeability
		LS=external_reluctances[counter].LS
		mu_elem=vacuum.mu0*mur
		reluctance_value=LS/mu_elem

		this_position=num_meshed_rel-number_deleted+counter
		faces_rel_spare[this_position,this_position]=reluctance_value
		fmm_sparse[this_position]=external_reluctances[counter].fmm
		source_flux_sparse[this_position]=external_reluctances[counter].flux


	external_nodes_list=list()

	for each in external_reluctances:

#Get the list of external nodes
		if each.node_from not in external_nodes_list:
			external_nodes_list.append(each.node_from)
		if each.node_to not in external_nodes_list:
			external_nodes_list.append(each.node_to)

#create a new face in the faces_list
		new_face=Face([],each.node_from+number_elements,each.node_to+number_elements)
		faces_list.append(new_face)

#Get the list of external nodes
	for each in coupling:
		if each.Node not in external_nodes_list:
			external_nodes_list.append(each.Node )

	print_message("External faces - Done")


#%% Incidence matrix
	print_message("Incidence matrix")
	external_nodes=0

	if run_external_circuit:
		external_nodes+=len(external_nodes_list)
#	elif run_surface_integral:
#		external_nodes+=len(BC_nodes)
	else:
		external_nodes+=0

	number_faces_list=len(faces_list)
	total_nodes=number_elements+external_nodes

	rows_incidence_sparse=list()
	cols_incidence_sparse=list()
	data_incidence_sparse=list()

	for counter in xrange(number_faces_list):
		this_face=faces_list[counter]
		rows_incidence_sparse.append(this_face.elem_1)
		cols_incidence_sparse.append(counter)
		data_incidence_sparse.append(1.0)

		rows_incidence_sparse.append(this_face.elem_2)
		cols_incidence_sparse.append(counter)
		data_incidence_sparse.append(-1.0)

	incidence_matrix_sparse=csr_matrix((data_incidence_sparse, (rows_incidence_sparse, cols_incidence_sparse)), shape=(total_nodes,number_faces_list))
	print_message("Incidence matrix - Done")


#%%Plot test fields
	Gmsh_file_name="test_H_field.txt"
	path=os.path.join(results_path,Gmsh_file_name)
	Create_Vector_field(plot_test_coord,plot_field,path,"H test")

	Gmsh_file_name="test_W.txt"
	path=os.path.join(results_path,Gmsh_file_name)
	Create_Vector_field(plot_test_coord,plot_shape_functions,path,"Shape function")

	return faces_rel_spare,incidence_matrix_sparse,fmm_sparse,source_flux_sparse,faces_ID,results_path,faces_ID_deleted_list,faces_list,faces_deleted_list,BC_nodes,BC_values
def Get_Gauss_points_list(preProcData, does_write_file, folder_path):
    '''
	Get the coordinates of the Guass points for all elements\n
	Return: list(array with the coordinates)\n
	PreProcData: The data from pre processing\n
	does_write_file: boolean. True: write the files containing the results\n
	folder_path: directory of the folder to write the file
	'''
    #==============================================================================
    # Pre-processor
    mesh_data = preProcData.MeshData
    all_elem_nodes = mesh_data.ElemNodes
    nodes_coordenates = mesh_data.NodesCoordenates
    elem_tags = mesh_data.ElemTags
    elem_type = mesh_data.ElemType

    gauss_points = GaussPoints()
    oper = Operations()

    number_elements = len(elem_tags)
    start_3D = 0
    number_gauss_points = 0
    max_number_points = 0

    for kl in xrange(number_elements):
        if elem_type[kl] <= 3:
            start_3D += 1
        else:
            this_gauss_points = gauss_points.get_gauss_points(elem_type[kl])
            number_gauss_points += float(this_gauss_points.shape[0])
            number_gauss_points_element = float(this_gauss_points.shape[1])
            if number_gauss_points_element > max_number_points:
                max_number_points = number_gauss_points_element

    gauss_points_coordinates = np.zeros(
        (number_gauss_points, max_number_points))

    point_counter = 0
    points_ID_list = list()
    phys_region_list = list()
    for kl in range(start_3D, number_elements):
        integPoints = gauss_points.get_gauss_points(elem_type[kl])
        numnodes = integPoints.shape[0]

        nodes = []
        for eachnode in xrange(numnodes):
            nodes.append(all_elem_nodes[kl][eachnode])
        elem_points_ID = list()
        elem_points_ID.append(kl)
        for integPoint in range(0, numnodes):
            u = integPoints[integPoint, 0]
            v = integPoints[integPoint, 1]
            p = integPoints[integPoint, 2]
            XYZ = oper.convert_local_real(elem_type[kl], u, v, p, nodes,
                                          nodes_coordenates)

            gauss_points_coordinates[point_counter][0] = XYZ[0]
            gauss_points_coordinates[point_counter][1] = XYZ[1]
            gauss_points_coordinates[point_counter][2] = XYZ[2]
            phys_region_list.append(elem_tags[kl][0])
            point_counter += 1
            elem_points_ID.append(int(point_counter - 1))
        points_ID_list.append(elem_points_ID)

#==============================================================================
# Folder results path
    file_names = File_names()
    results_folder = file_names.get_results_folder_name()
    results_path = os.path.join(folder_path, results_folder)
    path = os.path.join(results_path,
                        file_names.get_Gauss_points_list_file_name())
    path_IDs = os.path.join(results_path,
                            file_names.get_Gauss_Points_ID_file_name())
    path_Phys = os.path.join(
        results_path, file_names.get_Gauss_Points_Phys_region_file_name())

    write_numeric_file_numpy(path_Phys, phys_region_list)
    write_numeric_file_numpy(path, gauss_points_coordinates)
    write_numeric_file_numpy(path_IDs, points_ID_list)
    return gauss_points_coordinates, phys_region_list, points_ID_list
def run_permanent_magnets(preProcData, folder_path):
    print("Running permanent magnetic field solution")

#===============================================================================
# Initial data
#===============================================================================
#------------------------------------------------------------------------------
# Pre-processor
    mesh_data=preProcData.MeshData
    all_elem_nodes= mesh_data.ElemNodes
    elem_tags=mesh_data.ElemTags
    regions_material=preProcData.RegionMaterial
    materials_lib=get_materials_lib()
    elem_type=mesh_data.ElemType

    region_ID_list=list()
    counter=0
    for elem_counter in range(0,len(all_elem_nodes)):
        if elem_type[elem_counter]>3:
            for each_region in regions_material:
                if each_region.RegionNumber==elem_tags[counter][0]:
                    region_ID_list.append(each_region.MaterialName)
        counter+=1
    
    
    integ_gauss_points_coordinates=Get_Gauss_points_list(preProcData,True,folder_path)
    global_Hc_list=list()
    for elem_counter, each_element in enumerate(region_ID_list):
        local_Hc=list()
        for integ_point in range(0,len(integ_gauss_points_coordinates[elem_counter])):
            local_Hc.append(materials_lib[each_element].Hc)
        global_Hc_list.append(local_Hc)

    Hc_points_list=list()
    for each_element in global_Hc_list:
        for each_point in each_element:
                Hc_points_list.append((each_point))
    
    points_list=list()    
    global_nodes=list()
    counter=0

    for each_elem in integ_gauss_points_coordinates:
        local=list()        
        for each_point in each_elem:
            local.append(counter)
            counter+=1
            points_list.append(each_point)
        global_nodes.append(local)
        
#==============================================================================
# Folder results path
    file_names=File_names()
    results_folder=file_names.get_results_folder_name()
    folder_path=os.path.join(folder_path,results_folder)

#==============================================================================
# Write file with the results
    file_names=File_names()
    global_list=list()
    for eachw in Hc_points_list:
        global_list.append(eachw)
    h_field_results_file_name=file_names.get_H_results_file_name()
    full_path=os.path.join(folder_path,h_field_results_file_name)
#    print(global_list)
    write_numeric_data_file(full_path,global_list,"HResults",True)
    
    global_list=list()
    for eachw in global_nodes:
        local=list()
        for each in eachw:
            local.append(each)
        global_list.append(local)
    h_field_results_file_name=file_names.get_H_results_file_name()
    full_path=os.path.join(folder_path,h_field_results_file_name)
    write_numeric_data_file(full_path,global_list,"Points",False)

#==============================================================================
# GMSH post processing
    file_names=File_names()
    Gmsh_file_name=file_names.get_H_Gmsh_pos_proc_file_name()
    path=os.path.join(folder_path,Gmsh_file_name)
    global_coor=list()
    for each_element in integ_gauss_points_coordinates:
            for each_point in each_element:
                global_coor.append(each_point)

    Create_Vector_field(points_list,Hc_points_list,path,"H vector")
示例#7
0
def integrate_energy(pre_proc_data,results_path):

#Instances
	operations=Operations()
	mesh_data=pre_proc_data.MeshData
	get_gauss_points_class=GaussPoints()
	file_names=File_names()

	regions_material=pre_proc_data.RegionMaterial

#Mesh data
	nodes_coordenates=mesh_data.NodesCoordenates
	elem_tags=mesh_data.ElemTags
	elem_type=mesh_data.ElemType
	elem_nodes=mesh_data.ElemNodes
	number_elements=len(elem_tags)
	xy_plot=list()
	field=list()

#Reads flux file
	flux_results_file_name=file_names.flux_results_file_name()
	full_path=os.path.join(results_path,flux_results_file_name)
	new_flux=read_numeric_file_numpy(full_path)

#Read faces_ID
	faces_ID_file_name=file_names.get_faces_ID_file_name()
	full_path=os.path.join(results_path,faces_ID_file_name)
	data=get_data_from_file(full_path)
	faces_ID=get_file_block("$faces_ID","$Endfaces_ID",0,data,int)

#Read faces_from_to
	from_to_file_name=file_names.faces_from_to_file_name()
	full_path=os.path.join(results_path,from_to_file_name)
	faces_from_to=read_numeric_file_numpy(full_path)

	mu0=4.0*math.pi*math.pow(10.0,-7.0)
	materials_lib=get_materials_lib()
#Get the magnetic induction, based on the 3D elements interpolation
	energy=0
	counter=-1
	for elem_counter_3D in xrange(number_elements):
		this_elem_type_3D=elem_type[elem_counter_3D]
		nodes_list_3D= mesh_data.ElemNodes[elem_counter_3D]
		gauss_points=get_gauss_points_class.get_gauss_points(this_elem_type_3D)
		num_gauss_points=len(gauss_points)
		if this_elem_type_3D==4:
			counter=counter+1
			material_name=""
			for each_region in regions_material:
				if each_region.RegionNumber==elem_tags[elem_counter_3D][0]:
					material_name=each_region.MaterialName


			mur_r=materials_lib[material_name].Permeability
			mu_elem=mu0*mur_r
			wtri=get_gauss_points_class.get_integration_weight(this_elem_type_3D)

			for each_integ_point in xrange(num_gauss_points):
				u=gauss_points[each_integ_point,0]
				v=gauss_points[each_integ_point,1]
				p=gauss_points[each_integ_point,2]
				b_at_point=get_B_vector_point_uvp(u,v,p,elem_counter_3D,counter,elem_type,elem_nodes,faces_ID,nodes_coordenates,new_flux,faces_from_to)
#				b_at_point=np.array([b_at_point[0,0],b_at_point[1,0],b_at_point[2,0]])

				# Jacobian
				jac=operations.get_jacobian(this_elem_type_3D,nodes_list_3D,nodes_coordenates,u,v,p)
				det_jac=np.linalg.det(jac)
				abs_det_jac=np.abs(det_jac)

#					Element energy
				energy=energy+0.5*(1.0/mu_elem)*wtri*abs_det_jac*matrix_aux.dot_product(b_at_point,b_at_point)


#	Gmsh_file_name=file_names.get_B_Gmsh_surface_file_name()
#	path=os.path.join(results_path,Gmsh_file_name)
#	Create_Vector_field(xy_plot,field,path,"B Vector")

	return energy
示例#8
0
def run_Biot_Savart(setupFileName,meshFileName,folder_path):
    '''
    Runs the Biot-Savart method\n
    setupFileName: setup file name\n
    meshFileName: file name of the mesh\n
    folder_path: path of solution folder\n
    example:\n
    field_solution=Biot_Savart.run_Biot_Savart(setup_file_name,mesh_file_name,folder_path)
    '''
    print("Running Biot-Savart law")
    #===============================================================================
    # Pre Processing
    #===============================================================================
    preProcData= get_preproc_data(meshFileName, setupFileName)
    integ_gauss_points_coordinates=Get_Gauss_points_list(preProcData,True,folder_path)

    #===============================================================================
    # Initial data
    #===============================================================================
   
    # Setup
    regions_excitation=preProcData.RegionExcitation
    #------------------------------------------------------------------------------
    # Pre-processor
    mesh_data=preProcData.MeshData
    all_elem_nodes= mesh_data.ElemNodes
    nodes_coordenates=mesh_data.NodesCoordenates
    elem_tags=mesh_data.ElemTags
    elem_type=mesh_data.ElemType
    operations=Operations()
    
    global_nodes=list()
    counter=0
    global_values=list()
    
    for each_elem in integ_gauss_points_coordinates:
        local=list()
        for each_point in each_elem:
            local.append(np.array([0,0,0]))
        global_values.append(local)

    for elem_counter, each_element in  enumerate(all_elem_nodes):
        if elem_type[elem_counter]>1:      
            I=0
            for eachregion in regions_excitation:
                if eachregion.RegionNumber==elem_tags[elem_counter][0]:
                    Js=eachregion.Value
                    element_area=operations.get_area_element(elem_type[elem_counter],all_elem_nodes[elem_counter],nodes_coordenates)
                    I=math.fabs(Js*element_area)
                    break
            if I!=0:
                dl=np.array([0,0,Js/math.fabs(Js)])
																
#baricenter of the element with current density
                xbar=0
                ybar=0
                zbar=0
                nodes=all_elem_nodes[elem_counter]
                for nodeCounter in range(0,len(nodes)):
                    xbar=nodes_coordenates[nodes[nodeCounter]][0]+xbar
                    ybar=nodes_coordenates[nodes[nodeCounter]][1]+ybar
                    zbar=nodes_coordenates[nodes[nodeCounter]][2]+zbar
                num_nodes=len(nodes)
                baricenter_coordinates=np.array([xbar/num_nodes,ybar/num_nodes,zbar/num_nodes])

                local=list()        
                for elem_inner_counter, inner_elem_coodinates in enumerate(integ_gauss_points_coordinates):
                    for node_counter,each_node in enumerate(inner_elem_coodinates):
                        r= each_node-baricenter_coordinates
                        abs_r=LA.norm(r)
#==============================================================================
#                         Biot_savart equation
#==============================================================================
                        H_field=I*(1.0/(2.0*math.pi))*np.cross(dl,r)/math.pow(abs_r,2)
                        global_values[elem_inner_counter][node_counter]=global_values[elem_inner_counter][node_counter]+H_field
#List containing all the integration points coordinates
    points_list=list()  
    counter=0
    for each_elem in integ_gauss_points_coordinates:
        local=list()
        local_nodes=list()
        for each_point in each_elem:
            local.append(counter)
            points_list.append(each_point)
            local_nodes.append(counter)
            counter+=1
        global_nodes.append(local_nodes)

# Folder results path
    file_names=File_names()
    results_folder=file_names.get_results_folder_name()
    results_path=os.path.join(folder_path,results_folder)
#==============================================================================
# Write file with the results
    integPOintResults=list()
    for each_element in global_values:
        for each in  each_element:
            integPOintResults.append(each)
    counter=0
    h_field_results_file_name=file_names.get_H_results_file_name()
    full_path=os.path.join(results_path,h_field_results_file_name)
    write_numeric_data_file(full_path,integPOintResults,"HResults",True)

# Write file with the points numbering
    global_list=list()
    for eachw in global_nodes:
        local=list()
        for each in eachw:
            local.append(each)
        global_list.append(local)
    h_field_results_file_name=file_names.get_H_results_file_name()
    full_path=os.path.join(results_path,h_field_results_file_name)
    write_numeric_data_file(full_path,global_list,"Points",False)

#==============================================================================
# GMSH post processing
    Gmsh_file_name=file_names.get_H_Gmsh_pos_proc_file_name()
    path=os.path.join(results_path,Gmsh_file_name)
    Create_Vector_field(points_list,integPOintResults,path,"H vector")
示例#9
0
#folder_path=os.path.normpath(os.path.join(tests_folder,'37_Atuador_hor\\08_FFEM_fine'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'37_Atuador_hor\\09_FFEM_Circuit_coupling'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'37_Atuador_hor\\10_FFEM_Circuit_coupling_perfect'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'37_Atuador_hor\\02_BS_algo'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'38_convergence\\FFEM'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'39_H_discon\\FFEM_Complete'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'39_H_discon\\FFEM_Complete'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'34_Atuador_vert\\FFEM_3D_Acopla'))
folder_path = os.path.normpath(
    os.path.join(tests_folder, '40_3D_Winding\\algo'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'40_3D_Winding\\normal'))
setup_file = 'setup.txt'
mesh_file = 'model.msh'

#%% Pre processing
file_names = File_names()
results_folder = file_names.get_results_folder_name()
setup_file_name = os.path.join(folder_path, setup_file)
mesh_file_name = os.path.join(folder_path, mesh_file)
results_path = os.path.join(folder_path, results_folder)
pre_proc_data = get_preproc_data(mesh_file_name, setup_file_name)

#%%Processing
processing(folder_path, pre_proc_data)

#%%Post processing

#==============================================================================
# Plot B
#==============================================================================
tags_plot = list()
示例#10
0
#folder_path=os.path.normpath(os.path.join(tests_folder,'37_Atuador_hor\\04_FFEM_coarse'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'37_Atuador_hor\\08_FFEM_fine'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'37_Atuador_hor\\09_FFEM_Circuit_coupling'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'37_Atuador_hor\\10_FFEM_Circuit_coupling_perfect'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'37_Atuador_hor\\02_BS_algo'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'38_convergence\\FFEM'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'39_H_discon\\FFEM_Complete'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'39_H_discon\\FFEM_Complete'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'34_Atuador_vert\\FFEM_3D_Acopla'))
folder_path=os.path.normpath(os.path.join(tests_folder,'40_3D_Winding\\algo'))
#folder_path=os.path.normpath(os.path.join(tests_folder,'40_3D_Winding\\normal'))
setup_file='setup.txt'
mesh_file='model.msh'

#%% Pre processing
file_names=File_names()
results_folder=file_names.get_results_folder_name()
setup_file_name=os.path.join(folder_path,setup_file)
mesh_file_name =os.path.join(folder_path,mesh_file)
results_path=os.path.join(folder_path,results_folder)
pre_proc_data= get_preproc_data(mesh_file_name, setup_file_name)

#%%Processing
processing(folder_path,pre_proc_data)

#%%Post processing

#==============================================================================
# Plot B
#==============================================================================
tags_plot=list()
示例#11
0
def integrate_energy(pre_proc_data, results_path):

    #Instances
    operations = Operations()
    mesh_data = pre_proc_data.MeshData
    get_gauss_points_class = GaussPoints()
    file_names = File_names()

    regions_material = pre_proc_data.RegionMaterial

    #Mesh data
    nodes_coordenates = mesh_data.NodesCoordenates
    elem_tags = mesh_data.ElemTags
    elem_type = mesh_data.ElemType
    elem_nodes = mesh_data.ElemNodes
    number_elements = len(elem_tags)
    xy_plot = list()
    field = list()

    #Reads flux file
    flux_results_file_name = file_names.flux_results_file_name()
    full_path = os.path.join(results_path, flux_results_file_name)
    new_flux = read_numeric_file_numpy(full_path)

    #Read faces_ID
    faces_ID_file_name = file_names.get_faces_ID_file_name()
    full_path = os.path.join(results_path, faces_ID_file_name)
    data = get_data_from_file(full_path)
    faces_ID = get_file_block("$faces_ID", "$Endfaces_ID", 0, data, int)

    #Read faces_from_to
    from_to_file_name = file_names.faces_from_to_file_name()
    full_path = os.path.join(results_path, from_to_file_name)
    faces_from_to = read_numeric_file_numpy(full_path)

    mu0 = 4.0 * math.pi * math.pow(10.0, -7.0)
    materials_lib = get_materials_lib()
    #Get the magnetic induction, based on the 3D elements interpolation
    energy = 0
    counter = -1
    for elem_counter_3D in xrange(number_elements):
        this_elem_type_3D = elem_type[elem_counter_3D]
        nodes_list_3D = mesh_data.ElemNodes[elem_counter_3D]
        gauss_points = get_gauss_points_class.get_gauss_points(
            this_elem_type_3D)
        num_gauss_points = len(gauss_points)
        if this_elem_type_3D == 4:
            counter = counter + 1
            material_name = ""
            for each_region in regions_material:
                if each_region.RegionNumber == elem_tags[elem_counter_3D][0]:
                    material_name = each_region.MaterialName

            mur_r = materials_lib[material_name].Permeability
            mu_elem = mu0 * mur_r
            wtri = get_gauss_points_class.get_integration_weight(
                this_elem_type_3D)

            for each_integ_point in xrange(num_gauss_points):
                u = gauss_points[each_integ_point, 0]
                v = gauss_points[each_integ_point, 1]
                p = gauss_points[each_integ_point, 2]
                b_at_point = get_B_vector_point_uvp(u, v, p, elem_counter_3D,
                                                    counter, elem_type,
                                                    elem_nodes, faces_ID,
                                                    nodes_coordenates,
                                                    new_flux, faces_from_to)
                #				b_at_point=np.array([b_at_point[0,0],b_at_point[1,0],b_at_point[2,0]])

                # Jacobian
                jac = operations.get_jacobian(this_elem_type_3D, nodes_list_3D,
                                              nodes_coordenates, u, v, p)
                det_jac = np.linalg.det(jac)
                abs_det_jac = np.abs(det_jac)

                #					Element energy
                energy = energy + 0.5 * (
                    1.0 /
                    mu_elem) * wtri * abs_det_jac * matrix_aux.dot_product(
                        b_at_point, b_at_point)


#	Gmsh_file_name=file_names.get_B_Gmsh_surface_file_name()
#	path=os.path.join(results_path,Gmsh_file_name)
#	Create_Vector_field(xy_plot,field,path,"B Vector")

    return energy
示例#12
0
def Create_B_vector_plot(mesh_data, results_path, tags_plot):

    #Instances
    file_names = File_names()
    get_gauss_points_class = GaussPoints()

    #Reads flux file
    flux_results_file_name = file_names.flux_results_file_name()
    full_path = os.path.join(results_path, flux_results_file_name)
    new_flux = read_numeric_file_numpy(full_path)

    #Read faces_ID
    faces_ID_file_name = file_names.get_faces_ID_file_name()
    full_path = os.path.join(results_path, faces_ID_file_name)
    data = get_data_from_file(full_path)
    faces_ID = get_file_block("$faces_ID", "$Endfaces_ID", 0, data, int)

    #Read faces_from_to
    from_to_file_name = file_names.faces_from_to_file_name()
    full_path = os.path.join(results_path, from_to_file_name)
    faces_from_to = read_numeric_file_numpy(full_path)

    # Mesh data
    nodes_coordenates = mesh_data.NodesCoordenates
    elem_tags = mesh_data.ElemTags
    elem_type = mesh_data.ElemType
    elem_nodes = mesh_data.ElemNodes

    B_list = list()
    xy_plot = list()
    number_elements = len(elem_tags)
    operations = Operations()

    elements_3D_counter = 0
    for elem_counter in range(0, number_elements):
        run_this_element = False
        if tags_plot == "all" or elem_tags[elem_counter][0] in tags_plot:
            run_this_element = True

        if run_this_element and elem_type[elem_counter] > 3:
            this_elem_type = elem_type[elem_counter]

            #			gauss_points=get_gauss_points_class.get_gauss_points(this_elem_type)
            gauss_points = get_gauss_points_class.get_local_element_center_point(
                this_elem_type)
            #			number_integ_points=len(gauss_points)
            number_integ_points = 1
            this_element_nodes = elem_nodes[elem_counter]

            for each_integ_point in range(0, number_integ_points):

                u = gauss_points[each_integ_point, 0]
                v = gauss_points[each_integ_point, 1]
                p = gauss_points[each_integ_point, 2]
                xy_coord = operations.convert_local_real(
                    this_elem_type, u, v, p, this_element_nodes,
                    nodes_coordenates)
                xy_plot.append(xy_coord)
                b_at_point = get_B_vector_point_uvp(u, v, p, elem_counter,
                                                    elements_3D_counter,
                                                    elem_type, elem_nodes,
                                                    faces_ID,
                                                    nodes_coordenates,
                                                    new_flux, faces_from_to)
                B_list.append(
                    np.array(
                        [b_at_point[0, 0], b_at_point[1, 0], b_at_point[2,
                                                                        0]]))
            elements_3D_counter += 1

    Gmsh_file_name = file_names.get_Gmsh_B_field_file_name()
    path = os.path.join(results_path, Gmsh_file_name)
    Create_Vector_field(xy_plot, B_list, path, "B Vector")
示例#13
0
def integrate_B_surface(pre_proc_data, face_phys_ID, vol_phys_ID,
                        results_path):

    #Instances
    operations = Operations()
    mesh_data = pre_proc_data.MeshData
    get_gauss_points_class = GaussPoints()
    file_names = File_names()

    #Mesh data
    nodes_coordenates = mesh_data.NodesCoordenates
    elem_tags = mesh_data.ElemTags
    elem_type = mesh_data.ElemType
    elem_nodes = mesh_data.ElemNodes
    number_elements = len(elem_tags)
    xy_plot = list()
    field = list()

    #Reads flux file
    flux_results_file_name = file_names.flux_results_file_name()
    full_path = os.path.join(results_path, flux_results_file_name)
    new_flux = read_numeric_file_numpy(full_path)

    #Read faces_ID
    faces_ID_file_name = file_names.get_faces_ID_file_name()
    full_path = os.path.join(results_path, faces_ID_file_name)
    data = get_data_from_file(full_path)
    faces_ID = get_file_block("$faces_ID", "$Endfaces_ID", 0, data, int)

    #Read faces_from_to
    from_to_file_name = file_names.faces_from_to_file_name()
    full_path = os.path.join(results_path, from_to_file_name)
    faces_from_to = read_numeric_file_numpy(full_path)

    flux = 0
    for elem_counter in xrange(number_elements):
        this_elem_type = elem_type[elem_counter]
        if this_elem_type == 2 and elem_tags[elem_counter][0] == face_phys_ID:
            nodes_list_2D = mesh_data.ElemNodes[elem_counter]
            gauss_points = get_gauss_points_class.get_gauss_points(
                this_elem_type)
            num_gauss_points = len(gauss_points)

            #Area and normal vector of the 2D element
            node1 = elem_nodes[elem_counter][0]
            node2 = elem_nodes[elem_counter][1]
            node3 = elem_nodes[elem_counter][2]
            P1 = np.array([
                nodes_coordenates[node1][0], nodes_coordenates[node1][1],
                nodes_coordenates[node1][2]
            ])
            P2 = np.array([
                nodes_coordenates[node2][0], nodes_coordenates[node2][1],
                nodes_coordenates[node2][2]
            ])
            P3 = np.array([
                nodes_coordenates[node3][0], nodes_coordenates[node3][1],
                nodes_coordenates[node3][2]
            ])
            A = P2 - P1
            B = P3 - P1
            AxB = np.cross(A, B)
            nor = linalg.norm(AxB)
            n = AxB / nor
            area = 0.5 * nor

            #Get the real coordinates of the 2D element Gauss points
            xy_local = list()
            for each_integ_point in xrange(num_gauss_points):
                xyz = operations.convert_local_real(
                    this_elem_type, gauss_points[each_integ_point, 0],
                    gauss_points[each_integ_point,
                                 1], 0, nodes_list_2D, nodes_coordenates)
                xy_local.append(xyz)

#Get the magnetic induction, based on the 3D elements interpolation
            counter = -1
            B_list = list()
            for elem_counter_3D in xrange(number_elements):
                this_elem_type_3D = elem_type[elem_counter_3D]
                nodes_list_3D = mesh_data.ElemNodes[elem_counter_3D]
                if this_elem_type_3D == 4:
                    counter = counter + 1
                    if elem_tags[elem_counter_3D][0] == vol_phys_ID and set(
                            nodes_list_2D) < set(nodes_list_3D):
                        for xyz in xy_local:

                            #Convert the real coordinates of the 2D element into local coordinates
                            uvp = operations.convert_real_to_local(
                                elem_counter_3D, this_elem_type_3D, xyz[0],
                                xyz[1], xyz[2], nodes_list_3D,
                                nodes_coordenates)
                            xy_plot.append(xyz)
                            b_at_point = get_B_vector_point_uvp(
                                uvp[0], uvp[1], uvp[2], elem_counter_3D,
                                counter, elem_type, elem_nodes, faces_ID,
                                nodes_coordenates, new_flux, faces_from_to)
                            b_at_point = np.array([
                                b_at_point[0, 0], b_at_point[1, 0],
                                b_at_point[2, 0]
                            ])
                            field.append(b_at_point)
                            B_list.append(b_at_point)
                        break


#Integration process
            for each_integ_point in xrange(num_gauss_points):
                B = B_list[each_integ_point].dot(n)

                flux = flux + B * area / 3.0

    Gmsh_file_name = file_names.get_B_Gmsh_surface_file_name()
    path = os.path.join(results_path, Gmsh_file_name)
    Create_Vector_field(xy_plot, field, path, "B Vector")

    return flux
示例#14
0
def interpolated_along_line(vol_phys_ID, xyz_list, pre_proc_data,
                            results_path):
    operations = Operations()
    mesh_data = pre_proc_data.MeshData
    get_gauss_points_class = GaussPoints()
    shape_functions = ShapeFuncions()
    file_names = File_names()
    #Mesh data
    nodes_coordenates = mesh_data.NodesCoordenates
    elem_tags = mesh_data.ElemTags
    elem_type = mesh_data.ElemType
    elem_nodes = mesh_data.ElemNodes
    number_elements = len(elem_tags)
    xy_plot = list()
    field = list()

    #Reads flux file
    flux_results_file_name = file_names.flux_results_file_name()
    full_path = os.path.join(results_path, flux_results_file_name)
    new_flux = read_numeric_file_numpy(full_path)

    #Read faces_ID
    faces_ID_file_name = file_names.get_faces_ID_file_name()
    full_path = os.path.join(results_path, faces_ID_file_name)
    data = get_data_from_file(full_path)
    faces_ID = get_file_block("$faces_ID", "$Endfaces_ID", 0, data, int)

    #Read faces_from_to
    from_to_file_name = file_names.faces_from_to_file_name()
    full_path = os.path.join(results_path, from_to_file_name)
    faces_from_to = read_numeric_file_numpy(full_path)

    for xyz in xyz_list:
        counter = -1
        this_element = False
        for elem_counter in range(0, number_elements):
            this_elem_type = elem_type[elem_counter]
            if this_elem_type == 4:
                counter = counter + 1
                if elem_tags[elem_counter][0] in vol_phys_ID:
                    nodes_list = mesh_data.ElemNodes[elem_counter]
                    uvp = operations.convert_real_to_local(
                        elem_counter, this_elem_type, xyz[0], xyz[1], xyz[2],
                        nodes_list, nodes_coordenates)
                    N = shape_functions.get_node_shape_function(
                        this_elem_type, uvp[0], uvp[1], uvp[2])
                    if max(N) <= 1.0 and min(N) >= 0.0:
                        this_element = True

                        break
        if this_element:
            b_at_point = get_B_vector_point_uvp(uvp[0], uvp[1], uvp[2],
                                                elem_counter, counter,
                                                elem_type, elem_nodes,
                                                faces_ID, nodes_coordenates,
                                                new_flux, faces_from_to)
            b_at_point = np.array(
                [b_at_point[0, 0], b_at_point[1, 0], b_at_point[2, 0]])
            field.append(b_at_point)
        else:
            b_at_point = np.array([0.0, 0.0, 0.0])
            field.append(b_at_point)

    Gmsh_file_name = file_names.get_B_Gmsh_line_file_name()
    path = os.path.join(results_path, Gmsh_file_name)
    Create_Vector_field(xyz_list, field, path, "B Vector")

    Gmsh_file_name = "line_field.txt"
    path = os.path.join(results_path, Gmsh_file_name)
    write_numeric_file_numpy(path, field)
示例#15
0
def interpolated_along_line(vol_phys_ID,xyz_list,pre_proc_data,results_path):
	operations=Operations()
	mesh_data=pre_proc_data.MeshData
	get_gauss_points_class=GaussPoints()
	shape_functions=ShapeFuncions()
	file_names=File_names()
	#Mesh data
	nodes_coordenates=mesh_data.NodesCoordenates
	elem_tags=mesh_data.ElemTags
	elem_type=mesh_data.ElemType
	elem_nodes=mesh_data.ElemNodes
	number_elements=len(elem_tags)
	xy_plot=list()
	field=list()

	#Reads flux file
	flux_results_file_name=file_names.flux_results_file_name()
	full_path=os.path.join(results_path,flux_results_file_name)
	new_flux=read_numeric_file_numpy(full_path)

	#Read faces_ID
	faces_ID_file_name=file_names.get_faces_ID_file_name()
	full_path=os.path.join(results_path,faces_ID_file_name)
	data=get_data_from_file(full_path)
	faces_ID=get_file_block("$faces_ID","$Endfaces_ID",0,data,int)

	#Read faces_from_to
	from_to_file_name=file_names.faces_from_to_file_name()
	full_path=os.path.join(results_path,from_to_file_name)
	faces_from_to=read_numeric_file_numpy(full_path)

	for xyz in xyz_list:
		counter=-1
		this_element=False
		for elem_counter in range(0,number_elements):
			this_elem_type=elem_type[elem_counter]
			if this_elem_type==4:
				counter=counter+1
				if elem_tags[elem_counter][0] in vol_phys_ID:
					nodes_list= mesh_data.ElemNodes[elem_counter]
					uvp=operations.convert_real_to_local(elem_counter,this_elem_type,xyz[0],xyz[1],xyz[2],nodes_list,nodes_coordenates)
					N=shape_functions.get_node_shape_function(this_elem_type,uvp[0],uvp[1],uvp[2])
					if max(N)<=1.0 and min(N)>=0.0:
						this_element=True

						break
		if this_element:
			b_at_point=get_B_vector_point_uvp(uvp[0],uvp[1],uvp[2],elem_counter,counter,elem_type,elem_nodes,faces_ID,nodes_coordenates,new_flux,faces_from_to)
			b_at_point=np.array([b_at_point[0,0],b_at_point[1,0],b_at_point[2,0]])
			field.append(b_at_point)
		else:
			b_at_point=np.array([0.0,0.0,0.0])
			field.append(b_at_point)

	Gmsh_file_name=file_names.get_B_Gmsh_line_file_name()
	path=os.path.join(results_path,Gmsh_file_name)
	Create_Vector_field(xyz_list,field,path,"B Vector")

	Gmsh_file_name="line_field.txt"
	path=os.path.join(results_path,Gmsh_file_name)
	write_numeric_file_numpy(path,field)
def integration_process(folder_path, preProcData):
    file_names = File_names()
    results_folder = file_names.get_results_folder_name()
    results_path = os.path.join(folder_path, results_folder)

    #	Source field
    run_surface_integral = False
    run_biot_savart = True
    run_VS = False

    #%% Instances and geral definitions
    global_variables = GlobalVariables()
    error = Errors()
    operations = Operations()
    materials_lib = get_materials_lib()
    vacuum = Vacuum()
    get_gauss_points_class = GaussPoints()
    shape_functions = ShapeFuncions()
    operations = Operations()

    str_noflux_face = global_variables.str_noflux_face
    results_folder = file_names.get_results_folder_name()

    face = Face()
    #------------------------------------------------------------------------------
    # Setup
    regions_material = preProcData.RegionMaterial
    regions_excitation = preProcData.RegionExcitation
    boundary = preProcData.BC
    external_reluctances = preProcData.ExternalReluctances
    coupling = preProcData.CoupNet

    #------------------------------------------------------------------------------
    # Mesh
    mesh_data = preProcData.MeshData
    all_elem_nodes_3D = mesh_data.ElemNodes
    nodes_coordenates = mesh_data.NodesCoordenates
    elem_tags = mesh_data.ElemTags
    elem_type = mesh_data.ElemType

    #%% Get 2D and 3D elements, with their materials name
    elem_2D_ID = list()
    elem_type_3D = list()
    elem_nodes_3D = list()
    elem_tags_3D = list()
    region_ID_list_3D = list()
    number_elements_2D = 0

    for counter, each_elem in enumerate(all_elem_nodes_3D):
        this_elem_type = elem_type[counter]
        if this_elem_type < 4:
            elem_2D_ID.append(counter)
            number_elements_2D += 1
        else:
            elem_nodes_3D.append(each_elem)
            elem_type_3D.append(elem_type[counter])
            elem_tags_3D.append(elem_tags[counter])

            find = False
            for each_region in regions_material:
                if each_region.RegionNumber == elem_tags[counter][0]:
                    region_ID_list_3D.append(each_region.MaterialName)
                    find = True
            if not find:
                error.physical_surface_not_defined(
                    str(each_region.RegionNumber), elem_tags[counter][0])

    number_elements = len(elem_nodes_3D)
    number_nodes = len(nodes_coordenates)
    faces_ID = list()
    faces_list = list()
    plot_test_coord = list()
    plot_test_field = list()

    #%%Get source field
    field_solution = list()
    run_permanent_magnets = False

    #	Run Permanent Magnets
    for each_region in regions_material:
        for each in materials_lib[each_region.MaterialName].Hc:
            if each != 0.0:
                permanent_magnets.run_permanent_magnets(
                    preProcData, folder_path)
                run_permanent_magnets = True
                break

    #Read the fields
    if run_biot_savart or run_permanent_magnets:

        results_folder = file_names.get_results_folder_name()
        folder_name = os.path.join(folder_path, results_folder)

        #Gauss points IDs
        this_file_name = file_names.get_Gauss_points_ID_file_name()
        full_path = os.path.join(folder_name, this_file_name)
        points_IDs = np.genfromtxt(full_path,
                                   delimiter=' ',
                                   dtype='int',
                                   usecols=(1, 2, 3, 4))
        points_ID_elem_all = np.genfromtxt(full_path,
                                           delimiter=' ',
                                           dtype='int',
                                           usecols=(0))
        points_ID_elem = points_ID_elem_all - number_elements_2D
        points_ID_elem = points_ID_elem.tolist()
        points_ID_elem_all = points_ID_elem_all.tolist()

        #		Gauss points coordinates
        this_file_name = file_names.get_Gauss_points_coordinates_file_name()
        full_path = os.path.join(folder_name, this_file_name)
        coordinates = np.genfromtxt(full_path, delimiter=' ', dtype='double')

        #		Fields
        this_file_name = file_names.get_Gauss_points_H_field_file_name()
        #		this_file_name="H_source_FFEM.txt"

        full_path = os.path.join(folder_name, this_file_name)
        fields = np.genfromtxt(full_path, delimiter=' ', dtype='double')

        for elem_counter in range(0, number_elements):
            this_elem_type = elem_type_3D[elem_counter]
            gauss_points = get_gauss_points_class.get_gauss_points(
                this_elem_type)
            number_integ_points = len(
                get_gauss_points_class.get_gauss_points(this_elem_type))
            this_points_field = list()

            if elem_counter in points_ID_elem:

                this_elem = points_ID_elem.index(elem_counter)
                for k in points_IDs[this_elem].tolist():
                    Hxy = np.zeros((3, 1))
                    Hxy[0, 0] = fields[k, 0]
                    Hxy[1, 0] = fields[k, 1]
                    Hxy[2, 0] = fields[k, 2]
                    this_points_field.append(Hxy)

            else:
                for k in xrange(number_integ_points):
                    Hxy = np.zeros((3, 1))
                    this_points_field.append(Hxy)
            field_solution.append(this_points_field)

    run_external_circuit = False
    if len(coupling) > 0:
        run_external_circuit = True

#%%Creates the face list
    print_message("Creating faces list")
    for elem_counter in range(0, number_elements):
        number_local_faces = shape_functions.get_number_faces(this_elem_type)
        this_elem_type = elem_type_3D[elem_counter]
        this_element_nodes = elem_nodes_3D[elem_counter]
        faces_nodes_ID = shape_functions.get_nodes_ID_2_face(this_elem_type)
        number_faces, nodes_per_face = faces_nodes_ID.shape
        local_faces_ID = list()
        for local_face_counter in range(0, number_faces):
            nodes_list = list()
            for node_counter in range(nodes_per_face):
                node_ID = faces_nodes_ID[local_face_counter, node_counter]
                nodes_list.append(this_element_nodes[node_ID])
            local_faces_ID.append(
                face.add_to_list(nodes_list, elem_counter, faces_list))
        faces_ID.append(local_faces_ID)
    print_message("Creating faces list - Done")

    #%%Integration
    print_message("Integration process")

    num_meshed_rel = len(faces_list)
    num_non_meshed_rel = len(external_reluctances)
    num_total_rel = num_meshed_rel + num_non_meshed_rel

    #sparse matrix
    cols_rel_sparse = list()
    rows_rel_sparse = list()

    #reluctance matrix
    diagonal = list()
    for each_element_faces in faces_ID:
        numbre_faces_this_element = len(each_element_faces)
        for face_counter_1 in xrange(numbre_faces_this_element):
            pos_1 = each_element_faces[face_counter_1]
            for face_counter_2 in xrange(numbre_faces_this_element):
                pos_2 = each_element_faces[face_counter_2]
                if pos_1 == pos_2:
                    if pos_1 not in diagonal:
                        rows_rel_sparse.append(pos_1)
                        cols_rel_sparse.append(pos_2)
                        diagonal.append(pos_1)
                else:
                    rows_rel_sparse.append(pos_1)
                    cols_rel_sparse.append(pos_2)

    data_rel_sparse = np.zeros(len(rows_rel_sparse))
    faces_rel_spare = csr_matrix(
        (data_rel_sparse, (rows_rel_sparse, cols_rel_sparse)),
        shape=(num_total_rel, num_total_rel))

    #fmm matrix
    cols_fmm_sparse = np.zeros(num_meshed_rel)
    rows_fmm_sparse = xrange(0, num_meshed_rel)
    data_fmm_sparse = np.zeros(num_meshed_rel)
    fmm_sparse = csr_matrix(
        (data_fmm_sparse, (rows_fmm_sparse, cols_fmm_sparse)),
        shape=(num_total_rel, 1))

    #source_flux matrix
    cols_source_flux_sparse = np.zeros(num_meshed_rel)
    rows_source_flux_sparse = xrange(0, num_meshed_rel)
    data_source_flux_sparse = np.zeros(num_meshed_rel)
    source_flux_sparse = csr_matrix(
        (data_source_flux_sparse,
         (rows_source_flux_sparse, cols_source_flux_sparse)),
        shape=(num_total_rel, 1))
    #grad_phi matrix
    #	cols_grad_phi_sparse=np.zeros(num_meshed_rel)
    #	rows_grad_phi_sparse=xrange(0,num_meshed_rel)
    #	data_grad_phi_sparse=np.zeros(num_meshed_rel)
    #	grad_phi_sparse=csr_matrix((data_grad_phi_sparse, (rows_grad_phi_sparse, cols_grad_phi_sparse)), shape=(num_total_rel,1))

    this_elem_type = ""
    plot_field = list()
    plot_shape_functions = list()
    #	plot_test_coord=list()
    BC_nodes = list()
    BC_values = list()

    for elem_counter in xrange(number_elements):
        this_elem_type_changed = elem_type_3D[elem_counter]
        if this_elem_type != this_elem_type_changed:
            this_elem_type = this_elem_type_changed
            gauss_points = get_gauss_points_class.get_gauss_points(
                this_elem_type)
            number_local_faces = shape_functions.get_number_faces(
                this_elem_type)
            number_integ_points = len(
                get_gauss_points_class.get_gauss_points(this_elem_type))
            wtri = get_gauss_points_class.get_integration_weight(
                this_elem_type)

        faces_ID_Elem = faces_ID[elem_counter]
        this_element_nodes = elem_nodes_3D[elem_counter]
        mur_r = materials_lib[region_ID_list_3D[elem_counter]].Permeability
        mu_elem = vacuum.mu0 * mur_r
        #		x=nodes_coordenates[this_element_nodes[0]][1]

        # Get W at reference element
        w_local_this_element = list()  #[gauss point][face]
        for each_integ_point in xrange(number_integ_points):

            #u,v,w coordinates
            u = gauss_points[each_integ_point, 0]
            v = gauss_points[each_integ_point, 1]
            w = gauss_points[each_integ_point, 2]

            # Shape functions @ reference element
            w_local_this_point = shape_functions.get_facet_shape_function(
                this_elem_type, u, v, w)
            w_local_this_element.append(w_local_this_point)

# Shape functions @ real element for each face
        w_real_all_points = list(
        )  # w_real_lista[0] contains  the shape function of all points for face 0

        #Boundary conditions
        #		Hxy=field_solution[elem_counter][each_integ_point]
        #		if Hxy[0,0]!=0 or Hxy[1,0]!=0 or Hxy[2,0]!=0:
        #			BC_nodes.append(elem_counter)
        #			BC_values.append(x)

        #   Face 0...Fn
        #P0  W
        #Pn

        for face_counter in xrange(number_local_faces):
            w_real_this_point = list()
            for point_counter in range(0, number_integ_points):
                w_local = w_local_this_element[point_counter][face_counter]
                w_real = operations.convert_local_real_Piola(
                    this_elem_type, w_local[0, 0], w_local[0, 1],
                    w_local[0, 2], this_element_nodes, nodes_coordenates)
                w_real_this_point.append(w_real)
            w_real_all_points.append(w_real_this_point)

# Source fields
        for local_face_counter in xrange(number_local_faces):

            w_1 = copy.deepcopy(w_real_all_points[local_face_counter])
            face_ID_1 = faces_ID_Elem[local_face_counter]

            if faces_list[face_ID_1].elem_2 == elem_counter:
                for each in w_1:
                    each = matrix_aux.invert_w(each)

            elem_ID_all = elem_counter + number_elements_2D

            #			this_3D_ID=points_ID_elem_all.index(elem_ID_all)
            # mmf source integration process
            source = 0
            this_face_nodes = faces_list[face_ID_1].nodes_list
            #
            #
            this_elem = points_ID_elem.index(elem_counter)
            this_gauss_points_ID = points_IDs[this_elem].tolist()

            Hxy = np.zeros((3, 1))
            for each_integ_point in xrange(number_integ_points):
                if run_biot_savart or run_permanent_magnets:
                    #					Hxy=field_solution[elem_counter][each_integ_point]
                    this_point_ID = this_gauss_points_ID[each_integ_point]
                    Hxy[0, 0] = fields[this_point_ID, 0]
                    Hxy[1, 0] = fields[this_point_ID, 1]
                    Hxy[2, 0] = fields[this_point_ID, 2]

                    if Hxy[0, 0] != 0 or Hxy[1, 0] != 0 or Hxy[2, 0] != 0:

                        w_1_this_point = w_1[each_integ_point]

                        #u,v,p coordinates
                        u = gauss_points[each_integ_point, 0]
                        v = gauss_points[each_integ_point, 1]
                        p = gauss_points[each_integ_point, 2]
                        w = w_1_this_point

                        plot_shape_functions.append(w)

                        plot_test_field.append(Hxy)
                        plot_test_coord.append(coordinates[this_point_ID])
                        # Jacobian
                        jac = operations.get_jacobian(this_elem_type,
                                                      this_element_nodes,
                                                      nodes_coordenates, u, v,
                                                      p)
                        det_jac = np.linalg.det(jac)
                        abs_det_jac = np.abs(det_jac)
                        #Integration
                        source = source + wtri * abs_det_jac * matrix_aux.dot_product(
                            w, Hxy)

            fmm_sparse[face_ID_1, 0] = fmm_sparse[face_ID_1, 0] + source

            # Relutances integration process
            for local_face_counter_2 in xrange(number_local_faces):
                w_2 = copy.deepcopy(w_real_all_points[local_face_counter_2])
                face_ID_2 = faces_ID_Elem[local_face_counter_2]

                if faces_list[face_ID_2].elem_2 == elem_counter:
                    for each in w_2:
                        each = matrix_aux.invert_w(each)

                wtot = 0.0
                for each_integ_point in range(0, number_integ_points):
                    u = gauss_points[each_integ_point, 0]
                    v = gauss_points[each_integ_point, 1]
                    p = gauss_points[each_integ_point, 2]

                    # Jacobian
                    jac = operations.get_jacobian(this_elem_type,
                                                  this_element_nodes,
                                                  nodes_coordenates, u, v, p)
                    det_jac = np.linalg.det(jac)
                    abs_det_jac = np.abs(det_jac)

                    # Reluctance
                    w_1_this_point = w_1[each_integ_point]
                    w_2_this_point = w_2[each_integ_point]
                    wtot = wtot + wtri * abs_det_jac * matrix_aux.dot_product(
                        w_1_this_point, w_2_this_point) / mu_elem

                faces_rel_spare[face_ID_1, face_ID_2] += wtot
    print_message("Integration process - Done")

    #%% Connection between the physical line with the circuit node
    print_message("External faces")

    for counter, each_face in enumerate(faces_list):
        if each_face.elem_2 == str_noflux_face:
            for each_face_con in elem_2D_ID:
                nodes_face_shared = all_elem_nodes_3D[each_face_con]
                phys_line = elem_tags[each_face_con][0]

                #Coupling with external reluctances
                for each_coupling in coupling:
                    if each_coupling.PhysLine == phys_line:

                        bool_connect = True
                        for each_node_this_face in each_face.nodes_list:
                            if each_node_this_face not in nodes_face_shared:
                                bool_connect = False

                        if bool_connect:
                            # Redefine the face
                            new_face = Face(
                                each_face.nodes_list, each_face.elem_1,
                                each_coupling.Node + number_elements)
                            faces_list[counter] = new_face
                            each_coupling.Face_ID_List.append(counter)

#%% Insert the flux sources
#	BC_nodes=list()
    if run_surface_integral:
        folder_name = os.path.join(folder_path, results_folder)
        full_path = os.path.join(folder_name, "flux_surface.txt")
        flux_data = np.genfromtxt(full_path, delimiter=' ', dtype='double')
        flux_source = flux_data[:, 1]
        flux_source_elem_ID = flux_data[:, 0]
        num_faces_surface_integral = len(flux_source_elem_ID)
        external_node_surface_ID_counter = 0

        for face_counter in xrange(num_faces_surface_integral):
            this_elem_face_ID = int(flux_source_elem_ID[face_counter])
            this_face_nodes_elem = set(all_elem_nodes_3D[this_elem_face_ID])

            for counter, each_face in enumerate(faces_list):
                this_face_nodes = set(each_face.nodes_list)
                if this_face_nodes_elem.issubset(this_face_nodes):
                    #					print this_elem_face_ID
                    #					external_node_surface_ID=len(coupling)+number_elements-1
                    #					BC_nodes.append(external_node_surface_ID)
                    #					external_node_surface_ID_counter+=1
                    new_face = Face(each_face.nodes_list, each_face.elem_1,
                                    each_face.elem_2)
                    faces_list[counter] = new_face
                    source_flux_sparse[counter] = flux_source[face_counter]
                    faces_rel_spare[counter, counter] = 10000000000000000.0
                    fmm_sparse[counter, 0] = 0.0
#					print each_face.elem_1
#					break

#	BC_values=[0]*len(BC_nodes)

#%% Delete the faces without external connections
    faces_ID_deleted_list = list()
    faces_deleted_list = list()

    #Delete from reluctances and fmm matrix
    counter = 0
    for face_counter in xrange(len(faces_list)):
        if faces_list[face_counter].elem_2 == str_noflux_face:
            faces_ID_deleted_list.append(face_counter)

    faces_rel_spare = matrix_aux.delete_sparse_mask(faces_rel_spare,
                                                    faces_ID_deleted_list, 0)
    faces_rel_spare = matrix_aux.delete_sparse_mask(faces_rel_spare,
                                                    faces_ID_deleted_list, 1)
    fmm_sparse = matrix_aux.delete_sparse_mask(fmm_sparse,
                                               faces_ID_deleted_list, 0)
    source_flux_sparse = matrix_aux.delete_sparse_mask(source_flux_sparse,
                                                       faces_ID_deleted_list,
                                                       0)

    ##Delete from faces_list
    counter = 0
    for each in faces_ID_deleted_list:
        face_ID = each + counter
        this_face = faces_list[face_ID]
        faces_list.remove(this_face)
        faces_deleted_list.append(this_face)
        counter -= 1

#%% Add the external circuit reluctances
    number_deleted = len(faces_deleted_list)
    for counter in xrange(num_non_meshed_rel):

        #reluctance value
        material = external_reluctances[counter].Material
        mur = materials_lib[material].Permeability
        LS = external_reluctances[counter].LS
        mu_elem = vacuum.mu0 * mur
        reluctance_value = LS / mu_elem

        this_position = num_meshed_rel - number_deleted + counter
        faces_rel_spare[this_position, this_position] = reluctance_value
        fmm_sparse[this_position] = external_reluctances[counter].fmm
        source_flux_sparse[this_position] = external_reluctances[counter].flux

    external_nodes_list = list()

    for each in external_reluctances:

        #Get the list of external nodes
        if each.node_from not in external_nodes_list:
            external_nodes_list.append(each.node_from)
        if each.node_to not in external_nodes_list:
            external_nodes_list.append(each.node_to)

#create a new face in the faces_list
        new_face = Face([], each.node_from + number_elements,
                        each.node_to + number_elements)
        faces_list.append(new_face)

#Get the list of external nodes
    for each in coupling:
        if each.Node not in external_nodes_list:
            external_nodes_list.append(each.Node)

    print_message("External faces - Done")

    #%% Incidence matrix
    print_message("Incidence matrix")
    external_nodes = 0

    if run_external_circuit:
        external_nodes += len(external_nodes_list)
#	elif run_surface_integral:
#		external_nodes+=len(BC_nodes)
    else:
        external_nodes += 0

    number_faces_list = len(faces_list)
    total_nodes = number_elements + external_nodes

    rows_incidence_sparse = list()
    cols_incidence_sparse = list()
    data_incidence_sparse = list()

    for counter in xrange(number_faces_list):
        this_face = faces_list[counter]
        rows_incidence_sparse.append(this_face.elem_1)
        cols_incidence_sparse.append(counter)
        data_incidence_sparse.append(1.0)

        rows_incidence_sparse.append(this_face.elem_2)
        cols_incidence_sparse.append(counter)
        data_incidence_sparse.append(-1.0)

    incidence_matrix_sparse = csr_matrix(
        (data_incidence_sparse,
         (rows_incidence_sparse, cols_incidence_sparse)),
        shape=(total_nodes, number_faces_list))

    print_message("Incidence matrix - Done")

    #%%Plot test fields
    Gmsh_file_name = "test_H_field.txt"
    path = os.path.join(results_path, Gmsh_file_name)
    Create_Vector_field(plot_test_coord, plot_test_field, path, "H test")

    Gmsh_file_name = "test_W.txt"
    path = os.path.join(results_path, Gmsh_file_name)
    Create_Vector_field(plot_test_coord, plot_shape_functions, path,
                        "Shape function")

    print_message("Saving matrices")
    np.save(os.path.join(results_path, "faces_rel_spare_algo"),
            faces_rel_spare.toarray())
    np.save(os.path.join(results_path, "fmm_sparse_algol"),
            fmm_sparse.toarray())
    np.save(os.path.join(results_path, "incidence_matrix_algo"),
            incidence_matrix_sparse.toarray())
    print_message("Saving matrices: Done")

    return faces_rel_spare, incidence_matrix_sparse, fmm_sparse, source_flux_sparse, faces_ID, results_path, faces_ID_deleted_list, faces_list, faces_deleted_list, BC_nodes, BC_values
示例#17
0
def integrate_B_surface(pre_proc_data,face_phys_ID,vol_phys_ID,results_path):

#Instances
	operations=Operations()
	mesh_data=pre_proc_data.MeshData
	get_gauss_points_class=GaussPoints()
	file_names=File_names()

#Mesh data
	nodes_coordenates=mesh_data.NodesCoordenates
	elem_tags=mesh_data.ElemTags
	elem_type=mesh_data.ElemType
	elem_nodes=mesh_data.ElemNodes
	number_elements=len(elem_tags)
	xy_plot=list()
	field=list()

#Reads flux file
	flux_results_file_name=file_names.flux_results_file_name()
	full_path=os.path.join(results_path,flux_results_file_name)
	new_flux=read_numeric_file_numpy(full_path)

#Read faces_ID
	faces_ID_file_name=file_names.get_faces_ID_file_name()
	full_path=os.path.join(results_path,faces_ID_file_name)
	data=get_data_from_file(full_path)
	faces_ID=get_file_block("$faces_ID","$Endfaces_ID",0,data,int)

#Read faces_from_to
	from_to_file_name=file_names.faces_from_to_file_name()
	full_path=os.path.join(results_path,from_to_file_name)
	faces_from_to=read_numeric_file_numpy(full_path)

	flux=0
	for elem_counter in xrange(number_elements):
		this_elem_type=elem_type[elem_counter]
		if this_elem_type==2 and elem_tags[elem_counter][0]==face_phys_ID:
			nodes_list_2D= mesh_data.ElemNodes[elem_counter]
			gauss_points=get_gauss_points_class.get_gauss_points(this_elem_type)
			num_gauss_points=len(gauss_points)

#Area and normal vector of the 2D element
			node1=elem_nodes[elem_counter][0]
			node2=elem_nodes[elem_counter][1]
			node3=elem_nodes[elem_counter][2]
			P1=np.array([nodes_coordenates[node1][0],nodes_coordenates[node1][1],nodes_coordenates[node1][2]])
			P2=np.array([nodes_coordenates[node2][0],nodes_coordenates[node2][1],nodes_coordenates[node2][2]])
			P3=np.array([nodes_coordenates[node3][0],nodes_coordenates[node3][1],nodes_coordenates[node3][2]])
			A=P2-P1
			B=P3-P1
			AxB=np.cross(A,B)
			nor=linalg.norm(AxB)
			n=AxB/nor
			area=0.5*nor

#Get the real coordinates of the 2D element Gauss points
			xy_local=list()
			for each_integ_point in xrange(num_gauss_points):
				xyz=operations.convert_local_real(this_elem_type,gauss_points[each_integ_point,0],gauss_points[each_integ_point,1],0,nodes_list_2D,nodes_coordenates)
				xy_local.append(xyz)

#Get the magnetic induction, based on the 3D elements interpolation
			counter=-1
			B_list=list()
			for elem_counter_3D in xrange(number_elements):
				this_elem_type_3D=elem_type[elem_counter_3D]
				nodes_list_3D= mesh_data.ElemNodes[elem_counter_3D]
				if this_elem_type_3D==4:
					counter=counter+1
					if elem_tags[elem_counter_3D][0]==vol_phys_ID and set(nodes_list_2D)<set(nodes_list_3D):
						for xyz in xy_local:

#Convert the real coordinates of the 2D element into local coordinates
							uvp=operations.convert_real_to_local(elem_counter_3D,this_elem_type_3D,xyz[0],xyz[1],xyz[2],nodes_list_3D,nodes_coordenates)
							xy_plot.append(xyz)
							b_at_point=get_B_vector_point_uvp(uvp[0],uvp[1],uvp[2],elem_counter_3D,counter,elem_type,elem_nodes,faces_ID,nodes_coordenates,new_flux,faces_from_to)
							b_at_point=np.array([b_at_point[0,0],b_at_point[1,0],b_at_point[2,0]])
							field.append(b_at_point)
							B_list.append(b_at_point)
						break
#Integration process
			for each_integ_point in xrange(num_gauss_points):
				B=B_list[each_integ_point].dot(n)

				flux=flux+B*area/3.0

	Gmsh_file_name=file_names.get_B_Gmsh_surface_file_name()
	path=os.path.join(results_path,Gmsh_file_name)
	Create_Vector_field(xy_plot,field,path,"B Vector")

	return flux
def integration_process(folder_path,preProcData):
	file_names=File_names()
	results_folder=file_names.get_results_folder_name()
	results_path=os.path.join(folder_path,results_folder)
	
#%% Instances and geral definitions
	aux_RNM=AuxMethodsRNM()
	global_variables=GlobalVariables()
	error=Errors()
	operations=Operations()
	materials_lib=get_materials_lib()
	vacuum=Vacuum()
	get_gauss_points_class=GaussPoints()
	shape_functions=ShapeFuncions()
	operations=Operations()
	
	str_noflux_face=global_variables.str_noflux_face
	open_circuit_reluctance=global_variables.magnetic_open_circuit_reluctance
	results_folder=file_names.get_results_folder_name()
	
	face=Face()
	#------------------------------------------------------------------------------
	# Setup
	regions_material=preProcData.RegionMaterial
	regions_excitation=preProcData.RegionExcitation
	boundary=preProcData.BC
	external_reluctances=preProcData.ExternalReluctances
	coupling=preProcData.CoupNet
	#------------------------------------------------------------------------------
	# Mesh
	mesh_data=preProcData.MeshData
	all_elem_nodes_3D= mesh_data.ElemNodes
	nodes_coordenates=mesh_data.NodesCoordenates
	elem_tags=mesh_data.ElemTags
	elem_type=mesh_data.ElemType
	
	#%%Get source field

	#Run Biot-Savart
	run_biot_savart=False
#	for eachregion in regions_excitation:
#		 if eachregion.Value != 0.0:
#			 field_solution=Biot_Savart.run_Biot_Savart(setup_file_name,mesh_file_name,folder_path)
	#		 run_biot_savart=True
	#		 break
	
	# Run Permanent Magnets
	run_permanent_magnets=False
	for each_region in regions_material:
		for each in materials_lib[each_region.MaterialName].Hc:
			if each !=0.0:
				field_solution=permanent_magnets.run_permanent_magnets(preProcData,folder_path)
				run_permanent_magnets=True
				break
	
	#Read the file
	if run_biot_savart or run_permanent_magnets:
		(H_field,H_field_elem_nodes_3D)=get_Field_solution(os.path.join(results_path,file_names.get_H_results_file_name()))
	
	run_external_circuit=False
	if len(coupling)>0:
		run_external_circuit=True
	
	
	#%% Get 2D and 3D elements, with their materials name
	elem_2D_ID=list()
	elem_type_3D=list()
	elem_nodes_3D=list()
	elem_tags_3D=list()
	region_ID_list_3D=list()
	number_elements_2D=0
	
	for counter,each_elem in enumerate(all_elem_nodes_3D):
		this_elem_type=elem_type[counter]
		if this_elem_type<4:
			elem_2D_ID.append(counter)
			number_elements_2D+=1
		else:
			elem_nodes_3D.append(each_elem)
			elem_type_3D.append(elem_type[counter])
			elem_tags_3D.append(elem_tags[counter])
			
			find=False
			for each_region in regions_material:
				if each_region.RegionNumber==elem_tags[counter][0]:
					region_ID_list_3D.append(each_region.MaterialName)
					find=True
			if not find:
			   error.physical_surface_not_defined(str(each_region.RegionNumber),elem_tags[counter][0])
	
	number_elements=len(elem_nodes_3D)
	number_nodes=len(nodes_coordenates)
	faces_ID=list()
	faces_list=list()
	
#%%Creates the face list
	print_message("Creating faces list")
	for elem_counter in range(0,number_elements):
		number_local_faces=shape_functions.get_number_faces(this_elem_type)
		this_elem_type=elem_type_3D[elem_counter]
		this_element_nodes=elem_nodes_3D[elem_counter]
		faces_nodes_ID=shape_functions.get_nodes_ID_2_face(this_elem_type)
		number_faces,nodes_per_face=faces_nodes_ID.shape
		local_faces_ID=list()								   
		for local_face_counter in range(0,number_faces):
			nodes_list=list()
			for node_counter in range(nodes_per_face):
				node_ID=faces_nodes_ID[local_face_counter,node_counter]
				nodes_list.append(this_element_nodes[node_ID])
			local_faces_ID.append(face.add_to_list(nodes_list,elem_counter,faces_list))
		faces_ID.append(local_faces_ID)
	print_message("Creating faces list - Done")


#%%Integration
	print_message("Integration process")

		
	num_meshed_rel=len(faces_list)
	num_non_meshed_rel=len(external_reluctances)
	num_total_rel=num_meshed_rel+num_non_meshed_rel
	
#sparse matrix
	cols_rel_sparse=list()
	rows_rel_sparse=list()

#reluctance matrix	
	diagonal=list()
	for each_element_faces in faces_ID:
		numbre_faces_this_element=len(each_element_faces)
		for face_counter_1 in xrange(numbre_faces_this_element):
			pos_1=each_element_faces[face_counter_1]
			for face_counter_2 in xrange(numbre_faces_this_element):
				pos_2=each_element_faces[face_counter_2]
				if faces_list[pos_1].elem_2!=str_noflux_face and faces_list[pos_1].elem_2!=str_noflux_face:
					if pos_1==pos_2:
						if pos_1 not in diagonal:
							rows_rel_sparse.append(pos_1)
							cols_rel_sparse.append(pos_2)
							diagonal.append(pos_1)
					else:
						rows_rel_sparse.append(pos_1)
						cols_rel_sparse.append(pos_2)

	data_rel_sparse=np.zeros(len(rows_rel_sparse))
	faces_rel_spare=csr_matrix((data_rel_sparse, (rows_rel_sparse, cols_rel_sparse)), shape=(num_meshed_rel, num_meshed_rel))
#fmm matrix		
	cols_fmm_sparse=np.zeros(num_meshed_rel)
	rows_fmm_sparse=xrange(0,num_meshed_rel)
	data_fmm_sparse=np.zeros(num_meshed_rel)
	fmm_sparse=csr_matrix((data_fmm_sparse, (rows_fmm_sparse, cols_fmm_sparse)), shape=(num_meshed_rel,1))
	
	
	
	faces_rel_matrix=np.zeros((num_meshed_rel,num_meshed_rel))
	faces_fmm_matrix=np.zeros((num_meshed_rel,1))
	xy_integ_points_list=list()
	W_integ_points_list=list()
	
	this_elem_type=""
	for elem_counter in xrange(number_elements):
		this_elem_type_changed=elem_type_3D[elem_counter]
		if this_elem_type!=this_elem_type_changed:
			this_elem_type=this_elem_type_changed
			gauss_points=get_gauss_points_class.get_gauss_points(this_elem_type)
			number_local_faces=shape_functions.get_number_faces(this_elem_type)
			number_integ_points=len(get_gauss_points_class.get_gauss_points(this_elem_type))
			wtri=get_gauss_points_class.get_integration_weight(this_elem_type)
	
		faces_ID_Elem=faces_ID[elem_counter]
		this_element_nodes=elem_nodes_3D[elem_counter]
		mu_elem=vacuum.mu0*materials_lib[region_ID_list_3D[elem_counter]].Permeability
	
	
# Get W at reference element 
		w_local_this_element=list() #[gauss point][face]
		for each_integ_point in xrange(number_integ_points):
	
#u,v,w coordinates
			u=gauss_points[each_integ_point,0]
			v=gauss_points[each_integ_point,1]
			w=gauss_points[each_integ_point,2]
			
# Shape functions @ reference element
			w_local_this_point=shape_functions.get_facet_shape_function(this_elem_type,u,v,w)
			w_local_this_element.append(w_local_this_point)
	
# Shape functions @ real element for each face
		w_real_all_points=list() # w_real_lista[0] contains  the shape function of all points for face 0

#   Face 0...Fn
#P0  W
#Pn	
		
		for face_counter in xrange(number_local_faces):
			w_real_this_point=list()
			for point_counter in  range(0,number_integ_points):
				w_local=w_local_this_element[point_counter][face_counter]
				w_real=operations.convert_local_real_Piola(this_elem_type,w_local[0,0],w_local[0,1],w_local[0,2],this_element_nodes,nodes_coordenates)
				w_real_this_point.append(w_real)
			w_real_all_points.append(w_real_this_point)

# Source fields	 
		if run_biot_savart or run_permanent_magnets:
			H_points=H_field_elem_nodes_3D[elem_counter]
	
		for local_face_counter in xrange(number_local_faces):
			
			w_1=copy.deepcopy(w_real_all_points[local_face_counter])
			face_ID_1=faces_ID_Elem[local_face_counter]
			
			if faces_list[face_ID_1].elem_2==elem_counter:
				for each in w_1:
					each=aux_RNM.invert_w(each)

# mmf source integration process
			source=0
			for each_integ_point in xrange(number_integ_points):
				w_1_this_point=w_1[each_integ_point]
				
				u=gauss_points[each_integ_point,0]
				v=gauss_points[each_integ_point,1]
				p=gauss_points[each_integ_point,2]
				w=w_1_this_point
				
	
				xy_coord=operations.convert_local_real(this_elem_type,u,v,p,this_element_nodes,nodes_coordenates)
				xy_integ_points_list.append(xy_coord)
				W_integ_points_list.append(w)
				
	
			
				if run_biot_savart or run_permanent_magnets:
					 H_point=H_points[each_integ_point]
					 Hx=H_field[H_point][0]
					 Hy=H_field[H_point][1]
					 Hz=H_field[H_point][2]
					 
					 if (Hx!=0) or (Hy!=0) or (Hz!=0) :
						 Hxy=np.array([[Hx],
								[Hy],
								[Hz]])
	
# Jacobian
						 jac=operations.get_jacobian(this_elem_type,this_element_nodes,nodes_coordenates,u,v)
						 det_jac=np.linalg.det(jac)
						 abs_det_jac=np.abs(det_jac)
	
						 source=source+wtri*abs_det_jac*aux_RNM.dot_product(w,Hxy)
	
	
			aux_RNM.fmm_matrix_control(face_ID_1,faces_fmm_matrix,source,False,faces_list,str_noflux_face)
			aux_RNM.fmm_matrix_control(face_ID_1,fmm_sparse,source,False,faces_list,str_noflux_face)
			fmm_sparse
	
# Relutances integration process
			for local_face_counter_2 in xrange(number_local_faces):
				w_2=copy.deepcopy(w_real_all_points[local_face_counter_2])
				face_ID_2=faces_ID_Elem[local_face_counter_2]
				 
				if faces_list[face_ID_2].elem_2==elem_counter:
					 for each in w_2:
						 each=aux_RNM.invert_w(each)			 
				 
				wtot=0.0
				for each_integ_point in range(0,number_integ_points):
					 u=gauss_points[each_integ_point,0]
					 v=gauss_points[each_integ_point,1]
					 p=gauss_points[each_integ_point,2]
					 
# Jacobian
					 jac=operations.get_jacobian(this_elem_type,this_element_nodes,nodes_coordenates,u,v,p)
					 det_jac=np.linalg.det(jac)
					 abs_det_jac=np.abs(det_jac)
	
# Reluctance
					 w_1_this_point=w_1[each_integ_point]
					 w_2_this_point=w_2[each_integ_point]
					 wtot=wtot+wtri*abs_det_jac*aux_RNM.dot_product(w_1_this_point,w_2_this_point)/mu_elem
					 
				aux_RNM.reluctance_matrix_control(face_ID_1,face_ID_2,faces_rel_matrix,wtot,False,faces_list,str_noflux_face)
				aux_RNM.reluctance_matrix_control(face_ID_1,face_ID_2,faces_rel_spare,wtot,False,faces_list,str_noflux_face)
	print_message("Integration process - Done")
	
# Connection between the physical line with the circuit node
	print_message("External faces") 
	magnetic_short_circuit_reluctance=global_variables.magnetic_short_circuit_reluctance
	
	for counter,each_face in enumerate(faces_list):
		if each_face.elem_2==str_noflux_face:
			for each_face_con in elem_2D_ID:
				nodes_face_shared=all_elem_nodes_3D[each_face_con]
				phys_line=elem_tags[each_face_con][0]
	
				for each_coupling in coupling:
					if each_coupling.PhysLine==phys_line:
	
						bool_connect=True
						for each_node_this_face in each_face.nodes_list:
							if each_node_this_face not in nodes_face_shared:
								bool_connect=False
			
						if bool_connect:

# Redefine the face
							   new_face=Face(each_face.nodes_list,each_face.elem_1,each_coupling.Node+number_elements)				
							   faces_list[counter]=new_face
							   each_coupling.Face_ID_List.append(counter)
							   
#Set the reluctance as a magnetic short circuit
#							   aux_RNM.reluctance_matrix_control(counter,counter,faces_rel_spare,magnetic_short_circuit_reluctance,False)


	
#%% Delete the faces without external connections
	faces_ID_deleted_list=list()
	faces_deleted_list=list()

	counter=0
#Delete from reluctances and fmm matrix
	for face_counter in  xrange(len(faces_list)):
		if faces_list[face_counter].elem_2==str_noflux_face:
			faces_ID_deleted_list.append(face_counter)
	
	faces_rel_matrix=np.delete(faces_rel_matrix, faces_ID_deleted_list, axis=0)  
	faces_rel_matrix=np.delete(faces_rel_matrix, faces_ID_deleted_list, axis=1)
	faces_fmm_matrix=np.delete(faces_fmm_matrix, faces_ID_deleted_list, axis=0)

##Delete from faces_list
	counter=0
	for each in faces_ID_deleted_list:
		face_ID=each+counter
		this_face=faces_list[face_ID]
		faces_list.remove(this_face)
		faces_deleted_list.append(this_face)
		counter-=1
	
#%% Add the external circuit reluctances
	external_nodes_list=list()
	rows,cols=faces_rel_matrix.shape
	for each in external_reluctances:
	
		mu_elem=vacuum.mu0*materials_lib[each.Material].Permeability
	
#Get the list of external nodes
		if each.node_from not in external_nodes_list:
			external_nodes_list.append(each.node_from)
		if each.node_to not in external_nodes_list:
			external_nodes_list.append(each.node_to)
	   
#add the reluctance in the matrix system
		row_matrix=np.zeros((1,cols))
		faces_rel_matrix=np.vstack((faces_rel_matrix,row_matrix))
		rows+=1
		col_matrix=np.zeros((rows,1))
		faces_rel_matrix=np.hstack((faces_rel_matrix,col_matrix))
		cols+=1
		faces_fmm_matrix=np.vstack((faces_fmm_matrix,each.fmm))
		
#reluctance value
		reluctance_value=each.LS/mu_elem
		faces_rel_matrix[rows-1,cols-1]=reluctance_value
	
#create a new face in the faces_list
		new_face=Face([],each.node_from+number_elements,each.node_to+number_elements)
		faces_list.append(new_face)
		
#Get the list of external nodes
	for each in coupling:
		if each.Node not in external_nodes_list:
			external_nodes_list.append(each.Node )
	
	print_message("External faces - Done")
#%% Incidence matrix
	print_message("Incidence matrix")
	external_nodes=0
	if run_external_circuit:
		external_nodes+=len(external_nodes_list)
	else:
		external_nodes+=0
	
	total_nodes=number_elements+external_nodes
	incidence_matrix=np.zeros((total_nodes,len(faces_list)))
	
	for counter,each_face in enumerate(faces_list):
		if each_face.elem_2!=str_noflux_face:
			incidence_matrix[each_face.elem_1,counter]=1
			incidence_matrix[each_face.elem_2,counter]=-1
		else:
			incidence_matrix[each_face.elem_1,counter]=1
			incidence_matrix[total_nodes-1,counter]=-1
	
	print_message("Incidence matrix - Done")
	
	return faces_ID,results_path,faces_rel_matrix,incidence_matrix,faces_fmm_matrix,faces_ID_deleted_list,faces_list,faces_deleted_list
示例#19
0
def Create_B_vector_plot(mesh_data,results_path,tags_plot):

#Instances
	file_names=File_names()
	get_gauss_points_class=GaussPoints()

#Reads flux file
	flux_results_file_name=file_names.flux_results_file_name()
	full_path=os.path.join(results_path,flux_results_file_name)
	new_flux=read_numeric_file_numpy(full_path)

#Read faces_ID
	faces_ID_file_name=file_names.get_faces_ID_file_name()
	full_path=os.path.join(results_path,faces_ID_file_name)
	data=get_data_from_file(full_path)
	faces_ID=get_file_block("$faces_ID","$Endfaces_ID",0,data,int)

#Read faces_from_to
	from_to_file_name=file_names.faces_from_to_file_name()
	full_path=os.path.join(results_path,from_to_file_name)
	faces_from_to=read_numeric_file_numpy(full_path)

# Mesh data
	nodes_coordenates=mesh_data.NodesCoordenates
	elem_tags=mesh_data.ElemTags
	elem_type=mesh_data.ElemType
	elem_nodes=mesh_data.ElemNodes


	B_list=list()
	xy_plot=list()
	number_elements=len(elem_tags)
	operations=Operations()

	elements_3D_counter=0
	for elem_counter in range(0,number_elements):
		run_this_element=False
		if tags_plot=="all" or elem_tags[elem_counter][0] in tags_plot:
			run_this_element=True

		if run_this_element and elem_type[elem_counter]>3:
			this_elem_type=elem_type[elem_counter]

#			gauss_points=get_gauss_points_class.get_gauss_points(this_elem_type)
			gauss_points=get_gauss_points_class.get_local_element_center_point(this_elem_type)
#			number_integ_points=len(gauss_points)
			number_integ_points=1
			this_element_nodes=elem_nodes[elem_counter]

			for each_integ_point in range(0,number_integ_points):

				u=gauss_points[each_integ_point,0]
				v=gauss_points[each_integ_point,1]
				p=gauss_points[each_integ_point,2]
				xy_coord=operations.convert_local_real(this_elem_type,u,v,p,this_element_nodes,nodes_coordenates)
				xy_plot.append(xy_coord)
				b_at_point=get_B_vector_point_uvp(u,v,p,elem_counter,elements_3D_counter,elem_type,elem_nodes,faces_ID,nodes_coordenates,new_flux,faces_from_to)
				B_list.append(np.array([b_at_point[0,0],b_at_point[1,0],b_at_point[2,0]]))
			elements_3D_counter+=1

	Gmsh_file_name=file_names.get_Gmsh_B_field_file_name()
	path=os.path.join(results_path,Gmsh_file_name)
	Create_Vector_field(xy_plot,B_list,path,"B Vector")
示例#20
0
def Get_Gauss_points_list(preProcData,does_write_file,folder_path):
	'''
	Get the coordinates of the Guass points for all elements\n
	Return: list(array with the coordinates)\n
	PreProcData: The data from pre processing\n
	does_write_file: boolean. True: write the files containing the results\n
	folder_path: directory of the folder to write the file
	'''
#==============================================================================
# Pre-processor
	mesh_data=preProcData.MeshData
	all_elem_nodes= mesh_data.ElemNodes
	nodes_coordenates=mesh_data.NodesCoordenates
	elem_tags=mesh_data.ElemTags
	elem_type=mesh_data.ElemType

	gauss_points=GaussPoints()
	oper=Operations()

	number_elements=len(elem_tags)
	start_3D=0
	number_gauss_points=0
	max_number_points=0

	for kl in xrange(number_elements):
		if elem_type[kl]<=3:
			start_3D+=1
		else:
			this_gauss_points=gauss_points.get_gauss_points(elem_type[kl])
			number_gauss_points+=float(this_gauss_points.shape[0])
			number_gauss_points_element=float(this_gauss_points.shape[1])
			if number_gauss_points_element>max_number_points:
				max_number_points=number_gauss_points_element

	gauss_points_coordinates=np.zeros((number_gauss_points,max_number_points))

	point_counter=0
	points_ID_list=list()
	phys_region_list=list()
	for kl in range (start_3D,number_elements):
		integPoints=gauss_points.get_gauss_points(elem_type[kl])
		numnodes=integPoints.shape[0]

		nodes=[]
		for eachnode in xrange(numnodes):
			nodes.append(all_elem_nodes[kl][eachnode])
		elem_points_ID=list()
		elem_points_ID.append(kl)
		for integPoint in range(0,numnodes):
			u=integPoints[integPoint,0]
			v= integPoints[integPoint,1]
			p= integPoints[integPoint,2]
			XYZ=oper.convert_local_real(elem_type[kl],u,v,p,nodes,nodes_coordenates)

			gauss_points_coordinates[point_counter][0]=XYZ[0]
			gauss_points_coordinates[point_counter][1]=XYZ[1]
			gauss_points_coordinates[point_counter][2]=XYZ[2]
			phys_region_list.append(elem_tags[kl][0])
			point_counter+=1
			elem_points_ID.append(int(point_counter-1))
		points_ID_list.append(elem_points_ID)

#==============================================================================
# Folder results path
	file_names=File_names()
	results_folder=file_names.get_results_folder_name()
	results_path=os.path.join(folder_path,results_folder)
	path=os.path.join(results_path,file_names.get_Gauss_points_list_file_name())
	path_IDs=os.path.join(results_path,file_names.get_Gauss_Points_ID_file_name())
	path_Phys=os.path.join(results_path,file_names.get_Gauss_Points_Phys_region_file_name())



	write_numeric_file_numpy(path_Phys,phys_region_list)
	write_numeric_file_numpy(path,gauss_points_coordinates)
 	write_numeric_file_numpy(path_IDs,points_ID_list)
	return gauss_points_coordinates,phys_region_list,points_ID_list
def run_Biot_Savart(setupFileName, meshFileName, folder_path):
    '''
    Runs the Biot-Savart method\n
    setupFileName: setup file name\n
    meshFileName: file name of the mesh\n
    folder_path: path of solution folder\n
    example:\n
    field_solution=Biot_Savart.run_Biot_Savart(setup_file_name,mesh_file_name,folder_path)
    '''
    print("Running Biot-Savart law")
    #===============================================================================
    # Pre Processing
    #===============================================================================
    preProcData = get_preproc_data(meshFileName, setupFileName)
    integ_gauss_points_coordinates = Get_Gauss_points_list(
        preProcData, True, folder_path)

    #===============================================================================
    # Initial data
    #===============================================================================

    # Setup
    regions_excitation = preProcData.RegionExcitation
    #------------------------------------------------------------------------------
    # Pre-processor
    mesh_data = preProcData.MeshData
    all_elem_nodes = mesh_data.ElemNodes
    nodes_coordenates = mesh_data.NodesCoordenates
    elem_tags = mesh_data.ElemTags
    elem_type = mesh_data.ElemType
    operations = Operations()

    global_nodes = list()
    counter = 0
    global_values = list()

    for each_elem in integ_gauss_points_coordinates:
        local = list()
        for each_point in each_elem:
            local.append(np.array([0, 0, 0]))
        global_values.append(local)

    for elem_counter, each_element in enumerate(all_elem_nodes):
        if elem_type[elem_counter] > 1:
            I = 0
            for eachregion in regions_excitation:
                if eachregion.RegionNumber == elem_tags[elem_counter][0]:
                    Js = eachregion.Value
                    element_area = operations.get_area_element(
                        elem_type[elem_counter], all_elem_nodes[elem_counter],
                        nodes_coordenates)
                    I = math.fabs(Js * element_area)
                    break
            if I != 0:
                dl = np.array([0, 0, Js / math.fabs(Js)])

                #baricenter of the element with current density
                xbar = 0
                ybar = 0
                zbar = 0
                nodes = all_elem_nodes[elem_counter]
                for nodeCounter in range(0, len(nodes)):
                    xbar = nodes_coordenates[nodes[nodeCounter]][0] + xbar
                    ybar = nodes_coordenates[nodes[nodeCounter]][1] + ybar
                    zbar = nodes_coordenates[nodes[nodeCounter]][2] + zbar
                num_nodes = len(nodes)
                baricenter_coordinates = np.array(
                    [xbar / num_nodes, ybar / num_nodes, zbar / num_nodes])

                local = list()
                for elem_inner_counter, inner_elem_coodinates in enumerate(
                        integ_gauss_points_coordinates):
                    for node_counter, each_node in enumerate(
                            inner_elem_coodinates):
                        r = each_node - baricenter_coordinates
                        abs_r = LA.norm(r)
                        #==============================================================================
                        #                         Biot_savart equation
                        #==============================================================================
                        H_field = I * (1.0 / (2.0 * math.pi)) * np.cross(
                            dl, r) / math.pow(abs_r, 2)
                        global_values[elem_inner_counter][
                            node_counter] = global_values[elem_inner_counter][
                                node_counter] + H_field
#List containing all the integration points coordinates
    points_list = list()
    counter = 0
    for each_elem in integ_gauss_points_coordinates:
        local = list()
        local_nodes = list()
        for each_point in each_elem:
            local.append(counter)
            points_list.append(each_point)
            local_nodes.append(counter)
            counter += 1
        global_nodes.append(local_nodes)

# Folder results path
    file_names = File_names()
    results_folder = file_names.get_results_folder_name()
    results_path = os.path.join(folder_path, results_folder)
    #==============================================================================
    # Write file with the results
    integPOintResults = list()
    for each_element in global_values:
        for each in each_element:
            integPOintResults.append(each)
    counter = 0
    h_field_results_file_name = file_names.get_H_results_file_name()
    full_path = os.path.join(results_path, h_field_results_file_name)
    write_numeric_data_file(full_path, integPOintResults, "HResults", True)

    # Write file with the points numbering
    global_list = list()
    for eachw in global_nodes:
        local = list()
        for each in eachw:
            local.append(each)
        global_list.append(local)
    h_field_results_file_name = file_names.get_H_results_file_name()
    full_path = os.path.join(results_path, h_field_results_file_name)
    write_numeric_data_file(full_path, global_list, "Points", False)

    #==============================================================================
    # GMSH post processing
    Gmsh_file_name = file_names.get_H_Gmsh_pos_proc_file_name()
    path = os.path.join(results_path, Gmsh_file_name)
    Create_Vector_field(points_list, integPOintResults, path, "H vector")