Example #1
0
    def execute(self):

        #aqui vai o codigo
        #getting variables
        pts_grid = self.params['gridselectorbasic']['value']
        pts_props = self.params['orderedpropertyselector']['value'].split(';')
        grids_grid = self.params['gridselectorbasic_2']['value']
        grids_props = self.params['orderedpropertyselector_2']['value'].split(
            ';')
        flname_pts = self.params['filechooser']['value']
        flname_grid = self.params['filechooser_2']['value']

        if len(pts_props) != 0:
            x, y, z = np.array(sgems.get_X(pts_grid)), np.array(
                sgems.get_Y(pts_grid)), np.array(sgems.get_Z(pts_grid))
            vardict = {}
            for v in pts_props:
                values = np.array(sgems.get_property(pts_grid, v))
                vardict[v] = values
            pointsToVTK(flname_pts, x, y, z, data=vardict)
            print('Point set saved to {}'.format(flname_pts))

        if len(grids_props) != 0:
            X, Y, Z = grid_vertices(grids_grid)
            vardict = {}
            for v in grids_props:
                values = np.array(sgems.get_property(grids_grid, v))
                vardict[v] = values
            gridToVTK(flname_grid, X, Y, Z, cellData=vardict)
            print('Grid saved to {}'.format(flname_grid))

        return True
  def write_datafile_from_ar2gems(self):
    try:
      file=open(self.dict_gen_params['work_folder']+self.dict_gen_params['path_separator']+self.dict_gen_params['datafilename_with_property'],'w')
    except:
      print 'Problem opening requested par file for writing.'
      self.dict_gen_params['execution_status']='ERROR'
#      sys.exit(0)

    #get the data and weight, NOT CONSIDERING REGIONS YET
    data=sgems.get_property(self.dict_with_property['data_grid'],self.dict_with_property['data_property'])
    
    # if there is not weight, put just the data
    if self.dict_with_property['weight_property']=='':
      file.write('TITLE\n')
      file.write('1\n')
      file.write(self.dict_with_property['data_grid']+'\n')
      for item in data:
        file.write(str(item)+'\n')
      file.close()
    # put the data and the weight
    else:
      file.write('TITLE\n')
      file.write('2\n')
      file.write(self.dict_with_property['data_grid']+'\n')
      file.write(self.dict_with_property['weight_property']+'\n')
      data_weight=sgems.get_property(self.dict_with_property['weight_grid'],self.dict_with_property['weight_property'])
      # check if they have the same length
      if (len(data)==len(data_weight)):
        for x,y in zip(data,data_weight):
          file.write(str(x)+" "+str(y)+"\n")
      else:
        print "ERROR data and weight does not have the same lenght!"
        self.dict_gen_params['execution_status']='ERROR'
Example #3
0
    def execute(self):
      
        #aqui vai o codigo
        #getting variables
        prob_grid_name = self.params['gridselectorbasic']['value']
        prob_var_names = self.params['orderedpropertyselector']['value']

        sim_grid_name = self.params['gridselectorbasic_2']['value']
        sim_var_names = self.params['orderedpropertyselector_2']['value']
        
        tg_grid_name = sim_grid_name
        tg_prop_name = self.params['lineEdit']['value'] 

        prob_var_names_lst = prob_var_names.split(';')
        sim_var_names_lst = sim_var_names.split(';')

        
        codes = [int(i.split('_')[-3]) for i in prob_var_names_lst]

        probs_matrix = np.array([sgems.get_property(prob_grid_name, p) for p in prob_var_names_lst])
        reals = np.array([sgems.get_property(sim_grid_name, p) for p in sim_var_names_lst])
        norm_reals = [norm.cdf(lst) for lst in reals]

        #sampling cats
        print('Sampling categories using the p-fields and building realizations...')
        t1 = time.time()
        
        probs_matrix = probs_matrix.T
        for real_idx, r in enumerate(norm_reals):
            realization = []
            for idx, b in enumerate(np.array(r).T):
                if np.isnan(probs_matrix[idx]).any():
                    realization.append(float('nan'))
                else:
                    position = cat_random_sample(probs_matrix[idx], b)
                    realization.append(int(codes[position]))
            sgems.set_property(tg_grid_name, tg_prop_name+'_real_'+str(real_idx), realization)

        t2 = time.time()
        print('Took {} seconds'.format(round((t2-t1), 2)))

        print('Finished!')

        return True
Example #4
0
    def execute(self):
      
        #aqui vai o codigo
        #getting variables
        grid_name = self.params['rt_prop']['grid']
        prop_name = self.params['rt_prop']['property']
        prop_values = sgems.get_property(grid_name, prop_name)
        prop_values = np.array(prop_values)
        point_transform_type = self.params['comboBox']['value']

        if point_transform_type == 'Indicators':

            #calculating indicators
            nan_filter = np.isfinite(prop_values)
            unique_rts = np.unique(prop_values[nan_filter])

            for rt in unique_rts:
                print('calculating indicators for rock type {}'.format(int(rt)))
                ind_prop = prop_values == rt
                ind_prop = np.where(ind_prop == True, 1., 0.)
                ind_prop[~nan_filter] = float('nan')
                indprop_name = 'indicators_rt_{}'.format(int(rt))
                sgems.set_property(grid_name, indprop_name, ind_prop.tolist())

        else:

            x, y, z = np.array(sgems.get_X(grid_name)), np.array(sgems.get_Y(grid_name)), np.array(sgems.get_Z(grid_name))
            coords_matrix = np.vstack((x,y,z)).T

            #calculating signed distances
            nan_filter = np.isfinite(prop_values)
            unique_rts = np.unique(prop_values[nan_filter])

            for rt in unique_rts:
                print('calculating signed distances for rock type {}'.format(int(rt)))
                filter_0 = prop_values != rt
                filter_1 = prop_values == rt
                points_0 = coords_matrix[filter_0]
                points_1 = coords_matrix[filter_1]

                sd_prop = []
                for idx, pt in enumerate(prop_values):
                    if np.isnan(pt):
                        sd_prop.append(float('nan'))

                    else:
                        point = coords_matrix[idx]
                        if pt == rt:
                            sd_prop.append(-min_dist(point, points_0))
                        else:
                           sd_prop.append(min_dist(point, points_1)) 
            
                sgems.set_property(grid_name, 'signed_distances_rt_{}'.format(int(rt)), sd_prop)

        return True
Example #5
0
def isotopic_dataset(grid, prim_var, sec_var):
    var_matrix = []

    var_matrix.append(np.array((sgems.get_property(grid, prim_var))))

    for i in sec_var:
        p = sgems.get_property(grid, i)
        var_matrix.append(np.array(p))

    var_matrix = np.array(var_matrix)

    #removing variables that are not isotopic in relation with the primary
    lst_mask = list()
    for i, ref in enumerate(var_matrix[0]):
        if math.isnan(ref):
            pass
        else:
            lst_mask.append(np.isnan(var_matrix[:, i]))

    lst_mask = np.array(lst_mask)

    mask_f = lst_mask.sum(axis=0).astype('bool')

    var_isotopic_matrix = var_matrix[~mask_f]

    print "You are using ",len(var_isotopic_matrix)," variables."

    nan_indices= []
    for i,j in enumerate(var_isotopic_matrix[0]):
        if math.isnan(j):
            nan_indices.append(i)

    var_isotopic_matrix_trans = var_isotopic_matrix.T

    var_isotopic_final = []
    for i in var_isotopic_matrix_trans:
        if not math.isnan(i[0]):
            var_isotopic_final.append(i)

    var_isotopic_final = np.array(var_isotopic_final)

    return var_isotopic_final, nan_indices
Example #6
0
    def execute(self):
	print self.params
	# ESTABELECA OS PARAMETROS INICIAIS
	propertie = self.params['prop']['property']
	grid = self.params['prop']['grid']
	
	measured = float(self.params['Measured']['value'])
	Indicated = float(self.params['Indicated']['value'])
	Inferred = float(self.params['Inferred']['value'])
	dx = float(self.params['dx']['value'])
	dy = float(self.params['dy']['value'])
	dz = float(self.params['dz']['value'])
	
	grid = self.params['prop']['grid'] 
	x = sgems.get_property(grid, "_X_")
	y = sgems.get_property(grid, "_Y_")
	z = sgems.get_property(grid, "_Z_")
	distance = []
	
	

	numx = int(round((max(x) - min(x))/dx,0)) + 1
	numy = int(round((max(y) - min(y))/dy,0)) + 1
	numz = int(round((max(z) - min(z))/dz,0)) + 1

		

	cmd="NewCartesianGrid rescat::"+str(numx)+"::"+str(numy)+"::"+str(numz)+"::"+str(dx)+"::"+str(dy)+"::"+str(dz)+"::"+str(min(x))+"::"+str(min(y))+"::"+str(min(z))+"::0"
        print cmd
	sgems.execute(cmd)

	xh = sgems.get_property("rescat","_X_")
	yh = sgems.get_property("rescat","_Y_")
	zh = sgems.get_property("rescat","_Z_")	

	

	
	v = []
	for i, j, k in zip(xh,yh,zh):
		valores = 0
		menor_valor = 1000
		for xind, yind, zind in zip(x,y,z):
			distance = (math.sqrt((xind-i)**2+(yind-j)**2+(zind-k)**2))
			if (distance < measured):
				valores = 0
			elif( distance < Indicated and distance > measured):
				valores = 1
			elif(distance < Inferred and distance > Indicated):
				valores = 2
			else:
				valores = 3
			if (valores < menor_valor):
				menor_valor = valores		
		v.append(menor_valor)
	print (v)
	sgems.set_property("rescat","R",v)
	
	
    	return True 
    def execute(self):
        # d = np.array(sgems.get_property(self.grid_name,self.prop_name))
        # np.clip(d, -12, self.cap_value, out=d)
        # sgems.set_property(self.grid_name, self.out_name, d.tolist())
        print "executing..."

        inactive_flag = 0.0

        # Get grid dimensions
        ni, nj, nk = sgems.get_dims(self.grid_name)
        # Get user specified property:
        prop = sgems.get_property(self.grid_name, self.prop_name)

        property_values = []
        for k in range(nk - 1, -1, -1):
            for j in range(0, nj):
                for i in range(0, ni):
                    # node_id = sgems.get_nodeid(self.grid_name, i, j, k)
                    node_id = sgems.get_nodeid_from_ijk(self.grid_name, i, j, k)
                    if node_id != -1:
                        # grid block is active get property
                        property_values.append(prop[node_id])
                    else:
                        # grid block is inactive set inactive flag:
                        property_values.append(inactive_flag)


        full_file_name = os.path.join(self.location, self.filename)
        per_line = 10
        with open(full_file_name, 'w') as f:
            f.write("{}\n".format(self.header))
            cnt = 0
            for v in property_values:
                f.write("{}".format(v))
                cnt += 1
                if cnt % per_line == 0:
                    f.write("\n")
                else:
                    f.write(" ")
            f.write("/")
        print "{} values saved to file: {}".format(cnt, full_file_name)
        print "{} ...".format(property_values[0:min(10,len(property_values))])
        return True
Example #8
0
def neighb_value(grid, indice, dim_window, geomodel):

    dims_f = sgems.get_dims(grid)
    last_n = dims_f[0] * dims_f[1] * dims_f[2]
    last_ijk = sgems.get_ijk(grid, last_n - 1)
    ijk = sgems.get_ijk(grid, indice)
    geo_model = sgems.get_property(grid, geomodel)

    neighborhood = []
    for i in range(ijk[0] - (dim_window[0]), ijk[0] + (dim_window[0] + 1)):
        for j in range(ijk[1] - (dim_window[1]), ijk[1] + (dim_window[1] + 1)):
            for k in range(ijk[2] - (dim_window[1]),
                           ijk[2] + (dim_window[1] + 1)):
                ijk_blk = [i, j, k]
                neighborhood.append(ijk_blk)

    #print neighborhood

    valid_neighb = []
    for i in neighborhood:
        if 0 <= i[0] <= last_ijk[0] and 0 <= i[1] <= last_ijk[1] and 0 <= i[
                2] <= last_ijk[2]:
            valid_neighb.append(i)

    #print valid_neighb

    neighb_n = []
    for i in valid_neighb:
        neighb_n.append(ijk_in_n(grid, i[0], i[1], i[2]))

#print neighb_n

    cat_value = []
    for i in neighb_n:
        if not math.isnan(geo_model[i]):
            cat_value.append(int(geo_model[i]))

    #print cat_value, type(cat_value[0])

    return Most_Common(cat_value)
Example #9
0
 def execute(self):
   
     #aqui vai o codigo
     #getting variables
     grid_name = self.params['gridselectorbasic']['value']
     prop_names = self.params['orderedpropertyselector']['value'].split(';')
     gamma = float(self.params['doubleSpinBox']['value'])
     var_type = self.params['comboBox']['value']
     
     props_values = []
     for v in prop_names:
         props_values.append(sgems.get_property(grid_name, v))
     props_values = np.array(props_values)
     
     #calculating probs
     print('Calculating probabilities...')
     if var_type == "Signed Distances":
         print('Applying softmax transformation...')
         probs_matrix = np.array([sofmax_transformation(sds, gamma, var_type) for sds in props_values.T])
         probs_matrix = probs_matrix.T
         for i, p in enumerate(probs_matrix):
             sgems.set_property(grid_name, prop_names[i]+'_gamma_'+str(gamma), p.tolist())
     else:
         print('Correcting proportions...')
         probs_matrix = prob_correction(props_values)
         for i, p in enumerate(probs_matrix):
             sgems.set_property(grid_name, prop_names[i]+'_corrected_prop', p.tolist())
     
     #calculating entropy
     print('Calculating entropy...')
     entropies = [entropy(probs) for probs in probs_matrix.T]
     entropies = np.array(entropies)
     entropies = (entropies - np.nanmin(entropies))/(np.nanmax(entropies) - np.nanmin(entropies))
     sgems.set_property(grid_name, 'entropy_gamma_'+str(gamma), entropies.tolist())
     
     print('Done!')
     
     return True
Example #10
0
    def execute(self):

        grid = self.params['grid']['value']
        prop = self.params['prop']['value']

        dimx = int(self.params['x_dim']['value'])
        dimy = int(self.params['y_dim']['value'])
        dimz = int(self.params['z_dim']['value'])
        dim_window = [dimx, dimy, dimz]

        geo_model = sgems.get_property(grid, prop)

        geo_model_smooth = []
        for i in xrange(len(geo_model)):
            if math.isnan(geo_model[i]):
                geo_model_smooth.append(float('nan'))
            else:
                geo_model_smooth.append(
                    neighb_value(grid, i, [dimx, dimy, dimz], prop))

        create_variable(grid, 'Geomodel_smooth', geo_model_smooth)

        return True
Example #11
0
    def execute(self):
	print(self.params)

	'''
		EXPERIMENTAL VARIOGRAMS CALCULATION 
		_____________________________________________________________________________

		This is a template for SGems program for calculating experimental variograms.
		The user have to fill the parameters with a ui.file with same name of this python 
		file before start program. The QT userinterface connect SGems data with this routine
		using the class params.
		
		The output of this program is two files, one relatory with all experimental points 
		used in Automatic fitting procedure and other with a hml file used to import 
		experimental variograms in SGems

	AUTHOR: DAVID ALVARENGA DRUMOND 		2016
	
	'''	

	'''
	INITIAL PARAMETERS 
	______________________________________________________________________________

	All initial parameters are transcribe by ui.file interface. Variables are choose 
	among common variables. The follow variables are:

	COMMON VARIABLES: 

	head_property= adress of head property
	head_grid = adress of head grid 
	tail_property = adress of tail property
	tail_grid= adress of tail grid 
	C_variogram = check for variogram function calculation 
	C_covariance= check for covariance function calculation 
	C_relative_variogram = check for relative variogram calculation
	C_madogram = check for madogram calculation 
	C_correlogram = check for correlogram calculation 
	C_PairWise = check for pairwise calcluation 
	nlags= number of lags in experimental variogram 
	lagdistance = lenght of lag in experimental variogram 
	lineartolerance= linear tolerance of experimental variogram 
	htolerance = horizontal angular tolerance
	vtolerance = vertical angular tolerance
	hband = horizontal bandwidth
	vband = vertical bandwidth
	nAzimuths = number of azimuths 
	NDips = number of dips 
	Azimth_diference = angular diference between azimuths 
	Dip_difference = angular diference between dips
	sAzimuth = initial azimuth value
	sDip = initial dip value 
	inv = choose of invert correlogram axis 
	save = save adress of relatory file 
	save2 = save adress of Sgems variogram file 
	nhead = number of head to print in relatory file 
	ntail = number of tail to print in relatory file 

	
	'''

	# Stabilish initial parameters 

	head_property= self.params['head_prop']['property']
	head_grid = self.params['head_prop']['grid']
	tail_property = self.params['tail_prop']['property']
	tail_grid= self.params['tail_prop']['grid']
	C_variogram = int(self.params['C_variogram']['value'])
	C_covariance= int(self.params['C_covariance']['value'])
	C_relative_variogram = int(self.params['C_relative_variogram']['value'])
	C_madogram = int(self.params['C_madogram']['value'])
	C_correlogram = int(self.params['C_correlogram']['value'])
	C_PairWise = int(self.params['C_PairWise']['value'])
	nlags= int(self.params['nlags']['value'])
	lagdistance = float(self.params['lagdistance']['value'])
	lineartolerance= float(self.params['lineartolerance']['value'])
	htolerance = float(self.params['htolangular']['value'])
	vtolerance = float(self.params['vtolangular']['value'])
	hband = float(self.params['hband']['value'])
	vband = float(self.params['vband']['value'])
	nAzimuths = int(self.params['nAzimuths']['value'])
	NDips = int(self.params['NDips']['value'])
	Azimth_diference = float(self.params['Azimth_diference']['value'])
	Dip_difference = float(self.params['Dip_difference']['value'])
	sAzimuth = float(self.params['sAzimuth']['value'])
	sDip = float(self.params['sDip']['value'])
	inv = int(self.params['Inv']['value'])
	save = self.params['Save']['value']
	save2 = self.params['Save2']['value']
	nhead = self.params['NHEAD']['value']
	ntail = self.params['NTAIL']['value']
	
	# Obtain properties in SGems
	

	xh = []
	yh = []
	zh = [] 
	vh = []
	
	xh1 = sgems.get_property(head_grid, "_X_")
	yh1 = sgems.get_property(head_grid, "_Y_")
	zh1 = sgems.get_property(head_grid, "_Z_")
	vh1 = sgems.get_property(head_grid, head_property)	

	xh, yh, zh, vh = retire_nan(xh1,yh1,zh1,vh1)


	xt = []
	yt = []
	zt = []	
	vt = []

	xt1 = sgems.get_property(tail_grid, "_X_")
	yt1 = sgems.get_property(tail_grid, "_Y_")
	zt1 = sgems.get_property(tail_grid, "_Z_")
	vt1 = sgems.get_property(tail_grid, tail_property)

	xt, yt, zt, vt = retire_nan(xt1,yt1,zt1,vt1)	

	# Verify number of dimensions in the problem 
	
	# Verify number of dimensions in head 

	cdimensaoxh = False
	cdimensaoyh = False
	cdimensaozh = False

	for x in range(0,len(xh)):
		if (xh[x] != 0):
			cdimensaoxh = True


	for y in range(0,len(yh)):
		if (yh[y] != 0):
			cdimensaoyh = True


	for z in range(0,len(zh)):
		if (zh[z] != 0):
			cdimensaozh = True

	# Verify number of dimensions in tail 

	cdimensaoxt = False
	cdimensaoyt = False
	cdimensaozt = False

	for x in range(0,len(xt)):
		if (xt[x] != 0):
			cdimensaoxt = True

	for y in range(0,len(yt)):
		if (yt[y] != 0):
			cdimensaoyt = True


	for z in range(0,len(zt)):
		if (zt[z] != 0):
			cdimensaozt = True

	if ((cdimensaoxt == cdimensaoxh) and (cdimensaoyt == cdimensaoyh) and (cdimensaozt == cdimensaozh)):
		


		# Define maximum permissible distance
		
		dmaximo = (nlags + 0.5)*lagdistance
		
		#Transform tolerances if they are zero 

		if (htolerance == 0):
			htolerance= 45
		if (vtolerance == 0):
			vtolerance = 45
		if (hband == 0):
			hband = lagdistance/2
		if (vband == 0):
			vband = lagdistance/2
		if (lagdistance == 0):		
			lagdistance = 100
		if (lineartolerance == 0):
			lineartolerance = lagdistance/2
		
		
		#Convert tolerances in radians 
		htolerance = math.radians(htolerance)
		vtolerance = math.radians(vtolerance)	

		# Determine projections of Dip and Azimuth 
		htolerance = math.cos(htolerance)
		vtolerance = math.cos(vtolerance)
	
		# Define all direction distances 
		
		cabeca = []
		rabo = []
		cabeca2 =[]
		rabo2 = []
		distanciah =[]	
		distanciaxy =[]	
		distanciax =[]
		distanciay = []
 		distanciaz = []
		for t in range(0, len(yt)):
			for h in range(t, len(yh)):
				cabeca.append(vh[h])
				rabo.append(vt[t])
				cabeca2.append(vt[h])
				rabo2.append(vh[t])
				dx = xh[h]-xt[t] 				
				dy= yh[h]-yt[t]
				dz = zh[h]-zt[t]
				if (distanciah > 0):
					distanciay.append(dy)
					distanciax.append(dx)
					distanciaz.append(dz)
					distanciah.append(math.sqrt(math.pow(dy,2) + math.pow(dx,2) + math.pow(dz,2)))						
					distanciaxy.append(math.sqrt(math.pow(dy,2) + math.pow(dx,2)))

		# Calculate all sin and cosine functions of Dip and Azimuth 	
		

		
		azimute = []
		fAzimuth = float(Azimth_diference*(nAzimuths-1)) + sAzimuth 
		azimute = np.linspace(sAzimuth,fAzimuth,nAzimuths)
		

		dip = [] 
		fDip = Dip_difference*(NDips-1) + sDip
		dip = np.linspace(sDip,fDip,NDips)
	

		cos_Azimute=[]
		sin_Azimute=[]
		for a in azimute:
			cos_Azimute.append(math.cos(math.radians(90-a)))
			sin_Azimute.append(math.sin(math.radians(90-a)))
		cos_Dip =[]
		sin_Dip =[]
		for a in dip:	
			cos_Dip.append(math.cos(math.radians(90-a)))
			sin_Dip.append(math.sin(math.radians(90-a)))
	
		
		

		distancias_admissiveis = []
		azimute_admissiveis = []
		dip_admissiveis =[]
		v_valores_admissiveis_h =[]
		v_valores_admissiveis_t =[]
		v_valores_admissiveis_h2 =[]
		v_valores_admissiveis_t2 =[]
		pares = []		

		# Calculate admissible pairs  
		for a in range(0,len(azimute)):
			azm = azimute[a]
			for d in range(0, len(dip)):
				dipv = dip[d]
				for l in range(0, nlags):			
					valores_admissiveis_h = []
					valores_admissiveis_t = []
					valores_admissiveis_h2 =[]
					valores_admissiveis_t2 =[]
					distancia_admissivel = []
					azimute_admissivel =[]
					dip_admissivel=[]
					lag= lagdistance*(l+1)
					par= 0 
					for p in range(0,len(distanciah)):
						if (distanciah[p] < dmaximo):
							limitemin = lag - lineartolerance
							limitemax = lag + lineartolerance
							if (distanciah[p] > limitemin and distanciah[p] < limitemax):						
								if (distanciaxy[p] > 0.000): 				
									check_azimute = (distanciax[p]*cos_Azimute[a] +distanciay[p]*sin_Azimute[a])/distanciaxy[p]
								else:
									check_azimute = 1
								check_azimute = math.fabs(check_azimute)
								if (check_azimute >= htolerance):								
									check_bandh = (cos_Azimute[a]*distanciay[p]) - (sin_Azimute[a]*distanciax[p])
									check_bandh = math.fabs(check_bandh)
									if (check_bandh < hband):								
										if(distanciah[p] > 0.000):
											check_dip = (math.fabs(distanciaxy[p])*sin_Dip[d] + distanciaz[p]*cos_Dip[d])/distanciah[p]
										else:
											check_dip = 0.000
										check_dip = math.fabs(check_dip) 
										if (check_dip >= vtolerance):
											check_bandv = sin_Dip[d]*distanciaz[p] - cos_Dip[d]*math.fabs(distanciaxy[p])
											check_bandv = math.fabs(check_bandv)
											if (check_bandv < vband):
												if (check_dip < 0 and check_azimute < 0):
													valores_admissiveis_h.append(rabo[p])
													valores_admissiveis_t.append(cabeca[p])
													valores_admissiveis_h2.append(rabo2[p])
													valores_admissiveis_t2.append(cabeca2[p])
													distancia_admissivel.append(distanciah[p])
													par = par + 1	
													azimute_admissivel.append(azm)
													dip_admissivel.append(dipv)	
												else:
													valores_admissiveis_h.append(cabeca[p])
													valores_admissiveis_t.append(rabo[p])
													valores_admissiveis_h2.append(cabeca2[p])
													valores_admissiveis_t2.append(rabo2[p])
													distancia_admissivel.append(distanciah[p])
													par = par + 1	
													azimute_admissivel.append(azm)
													dip_admissivel.append(dipv)
					if (len(valores_admissiveis_h) > 0 and len(valores_admissiveis_t) > 0):			
						v_valores_admissiveis_h.append(valores_admissiveis_h)
						v_valores_admissiveis_h2.append(valores_admissiveis_h2)
						v_valores_admissiveis_t2.append(valores_admissiveis_t2)
						v_valores_admissiveis_t.append(valores_admissiveis_t)
						distancias_admissiveis.append(distancia_admissivel)
						pares.append(par)
						azimute_admissiveis.append(azimute_admissivel)	
						dip_admissiveis.append(dip_admissivel)

			

		# Calculate continuity functions 	

		# Variogram
		
		if (C_variogram == 1): 		
			continuidade =[]
			lag_adm =[]
			azimute_adm =[]
			dip_adm =[]
			for i in range(0,len(v_valores_admissiveis_h)):
				flutuantet =[]
				flutuanteh =[]
				flutuanteh2 = []
				flutuantet2 =[]
				flutuanted =[]
				flutuantea=[]
				flutuantedip=[]
				par_var = 0
				flutuanteh = v_valores_admissiveis_h[i][:]
				flutuanteh2= v_valores_admissiveis_h2[i][:]
				flutuantet = v_valores_admissiveis_t[i][:]
				flutuantet2 = v_valores_admissiveis_t2[i][:]
				flutuanted = distancias_admissiveis[i][:]
				flutuantea= azimute_admissiveis[i][:]
				flutuantedip = dip_admissiveis[i][:]
				par_var= pares[i]
				soma = 0
				lagmedio =0
				agmedio =0 
				dgmedio = 0
				for j in range(0, len(flutuanteh)):
					soma = soma + (flutuanteh[j] - flutuantet2[j])*(flutuanteh2[j]-flutuantet[j])/(2*pares[i])
				continuidade.append(soma)
				for z in range(0, len(flutuanted)):
					lagmedio = lagmedio + flutuanted[z]/len(flutuanted)
				lag_adm.append(lagmedio)
				for g in range(0, len(flutuantea)):
					agmedio = agmedio + flutuantea[g]/len(flutuantea)
				azimute_adm.append(agmedio)
				for t in range(0, len(flutuantedip)):
					dgmedio = dgmedio + flutuantedip[t]/len(flutuantedip)
				dip_adm.append(dgmedio)
				
			
			
		# Covariogram 
		if (C_covariance == 1): 		
			continuidade =[]
			lag_adm =[]
			azimute_adm =[]
			dip_adm =[]
			for i in range(0,len(v_valores_admissiveis_h)):
				flutuantet =[]
				flutuanteh =[]
				flutuanted =[]
				flutuantea=[]
				flutuantedip=[]
				par_var = 0
				flutuanteh = v_valores_admissiveis_h[i]
				flutuantet = v_valores_admissiveis_t[i]
				flutuanted = distancias_admissiveis[i]
				flutuantea= azimute_admissiveis[i]
				flutuantedip = dip_admissiveis[i]
				par_var= pares[i]
				soma = 0
				lagmedio =0
				agmedio =0 
				dgmedio = 0
				somah = 0
				somat = 0 
				mediah = 0
				mediat =0
				for d in range (0, len(flutuanteh)):
					somah = somah + flutuanteh[d]
				mediah = float(somah/len(flutuanteh))
				for t in range (0, len(flutuantet)):
					somat = somat + flutuantet[t]
				mediat = float(somat/len(flutuantet))
				for j in range(0, len(flutuanteh)):
					soma = soma + float(((flutuanteh[j] - mediah)*(flutuantet[j] - mediat))/(par_var))
				continuidade.append(soma)
				for z in range(0, len(flutuanted)):
					lagmedio = lagmedio + flutuanted[z]/len(flutuanted)
				lag_adm.append(lagmedio)
				for g in range(0, len(flutuantea)):
					agmedio = agmedio + flutuantea[g]/len(flutuantea)
				azimute_adm.append(agmedio)
				for y in range(0, len(flutuantedip)):
					dgmedio = dgmedio + flutuantedip[y]/len(flutuantedip)
				dip_adm.append(dgmedio)
				
		# Correlogram
		if (C_correlogram == 1): 		
			continuidade =[]
			lag_adm =[]
			azimute_adm =[]
			dip_adm =[]
			for i in range(0,len(v_valores_admissiveis_h)):
				flutuantet =[]
				flutuanteh =[]
				flutuanted =[]
				flutuantea=[]
				flutuantedip=[]
				par_var = 0
				flutuanteh = v_valores_admissiveis_h[i]
				flutuantet = v_valores_admissiveis_t[i]
				flutuanted = distancias_admissiveis[i]
				flutuantea= azimute_admissiveis[i]
				flutuantedip = dip_admissiveis[i]
				par_var= pares[i]
				soma = 0
				lagmedio =0
				agmedio =0 
				dgmedio = 0
				somah = 0
				somat = 0 
				diferencah =0
				diferencat =0
				mediah = 0
				mediat =0
				varh = 0
				vart = 0
				for d in range (0, len(flutuanteh)):
					somah = somah + flutuanteh[d]
				mediah = float(somah/len(flutuanteh))
				for t in range (0, len(flutuantet)):
					somat = somat + flutuantet[t]
				mediat = float(somat/len(flutuantet))
				for u in range(0, len(flutuanteh)):
					diferencah = flutuanteh[u]**2 + diferencah
				varh = math.sqrt(float(diferencah)/len(flutuanteh)-mediah**2)
				for m in range(0, len(flutuanteh)):
					diferencat = flutuantet[m]**2 + diferencat				
				vart = math.sqrt(float(diferencat)/len(flutuantet)-mediat**2)
				for j in range(0, len(flutuanteh)):
						if (vart > 0 and varh >0 ):
							if (inv == 1):
								soma = soma + 1-(flutuanteh[j] - mediah)*(flutuantet[j] - mediat)/(par_var*vart*varh)
							else:
								soma = soma + (flutuanteh[j] - mediah)*(flutuantet[j] - mediat)/(par_var*vart*varh)	
				continuidade.append(soma)
				for z in range(0, len(flutuanted)):
					lagmedio = lagmedio + flutuanted[z]/len(flutuanted)
				lag_adm.append(lagmedio)
				for g in range(0, len(flutuantea)):
					agmedio = agmedio + flutuantea[g]/len(flutuantea)
				azimute_adm.append(agmedio)
				for y in range(0, len(flutuantedip)):
					dgmedio = dgmedio + flutuantedip[y]/len(flutuantedip)
				dip_adm.append(dgmedio)

		# PairWise 
		if (C_PairWise == 1): 		
			continuidade =[]
			lag_adm =[]
			azimute_adm =[]
			dip_adm =[]
			for i in range(0,len(v_valores_admissiveis_h)):
				flutuantet =[]
				flutuanteh =[]
				flutuanted =[]
				flutuantea=[]
				flutuantedip=[]
				par_var = 0
				flutuanteh = v_valores_admissiveis_h[i][:]
				flutuantet = v_valores_admissiveis_t[i][:]
				flutuanted = distancias_admissiveis[i][:]
				flutuantea= azimute_admissiveis[i][:]
				flutuantedip = dip_admissiveis[i][:]
				par_var= pares[i]
				soma = 0
				lagmedio =0
				agmedio =0 
				dgmedio = 0
				for j in range(0, len(flutuanteh)):
					s = ((flutuanteh[j] - flutuantet[j])/(flutuanteh[j]+flutuantet[j]))**2
					soma = soma + 2*s/(1.0*par_var)
				continuidade.append(soma)
				for z in range(0, len(flutuanted)):
					lagmedio = lagmedio + flutuanted[z]/len(flutuanted)
				lag_adm.append(lagmedio)
				for g in range(0, len(flutuantea)):
					agmedio = agmedio + flutuantea[g]/len(flutuantea)
				azimute_adm.append(agmedio)
				for t in range(0, len(flutuantedip)):
					dgmedio = dgmedio + flutuantedip[t]/len(flutuantedip)
				dip_adm.append(dgmedio)
				
	
		# Relative Variogram
		if (C_relative_variogram  == 1): 		
			continuidade =[]
			lag_adm =[]
			azimute_adm =[]
			dip_adm =[]
			for i in range(0,len(v_valores_admissiveis_h)):
				flutuantet =[]
				flutuanteh =[]
				flutuanteh2 = []
				flutuantet2 =[]
				flutuanted =[]
				flutuantea=[]
				flutuantedip=[]
				par_var = 0
				flutuanteh = v_valores_admissiveis_h[i]
				flutuantet = v_valores_admissiveis_t[i]
				flutuanteh2 = v_valores_admissiveis_h2[i]
				flutuantet2 = v_valores_admissiveis_t2[i]
				flutuanted = distancias_admissiveis[i]
				flutuantea= azimute_admissiveis[i]
				flutuantedip = dip_admissiveis[i]
				par_var= pares[i]
				soma = 0
				lagmedio =0
				agmedio =0 
				dgmedio = 0
				somah = 0
				somat = 0 
				mediah = 0
				mediat =0
				for d in range (0, len(flutuanteh)):
					somah = somah + flutuanteh[d]
				mediah = float(somah/len(flutuanteh))
				for t in range (0, len(flutuantet)):
					somat = somat + flutuantet[t]
				mediat = float(somat/len(flutuantet))
				for j in range(0, len(flutuanteh)):
						soma = soma + float((flutuanteh[j] -flutuantet2[j])*(flutuanteh2[j] - flutuantet2[j])/(par_var*(mediat+mediah)**2/4))
				continuidade.append(soma)
				for z in range(0, len(flutuanted)):
					lagmedio = lagmedio + flutuanted[z]/len(flutuanted)
				lag_adm.append(lagmedio)
				for g in range(0, len(flutuantea)):
					agmedio = agmedio + flutuantea[g]/len(flutuantea)
				azimute_adm.append(agmedio)
				for y in range(0, len(flutuantedip)):
					dgmedio = dgmedio + flutuantedip[y]/len(flutuantedip)
				dip_adm.append(dgmedio)
		
		# Madogram 
		if (C_madogram == 1): 		
			continuidade =[]
			lag_adm =[]
			azimute_adm =[]
			dip_adm =[]
			for i in range(0,len(v_valores_admissiveis_h)):
				flutuantet =[]
				flutuanteh =[]
				flutuanted =[]
				flutuantea=[]
				flutuantedip=[]
				par_var = 0
				flutuanteh = v_valores_admissiveis_h[i]
				flutuantet = v_valores_admissiveis_t[i]
				flutuanted = distancias_admissiveis[i]
				flutuantea= azimute_admissiveis[i]
				flutuantedip = dip_admissiveis[i]
				par_var= pares[i]
				soma = 0
				lagmedio =0
				agmedio =0 
				dgmedio = 0
				for j in range(0, len(flutuanteh)):
						soma = soma + float(math.fabs(flutuanteh[j] - flutuantet[j])/(2*par_var))
				continuidade.append(soma)
				for z in range(0, len(flutuanted)):
					lagmedio = lagmedio + flutuanted[z]/len(flutuanted)
				lag_adm.append(lagmedio)
				for g in range(0, len(flutuantea)):
					agmedio = agmedio + flutuantea[g]/len(flutuantea)
				azimute_adm.append(agmedio)
				for t in range(0, len(flutuantedip)):
					dgmedio = dgmedio + flutuantedip[t]/len(flutuantedip)
				dip_adm.append(dgmedio)
		

		# Write experimental variograms in relatory 


		save= open(save,"a")
		save.write(nhead + "\n")
		save.write(ntail + "\n")
		save.write(" Azimuth	Dip	lag	variogram	pairs \n")
		for i in range(0, len(continuidade)):
			save.write(str(azimute_adm[i]) + "	" +str(dip_adm[i]) + "	" + str(lag_adm[i]) + "	" + str(continuidade[i])+ "	" + str(pares[i]) + "\n") 	

		# Separate experimental variograms according prescribe direction 

		posicao =[]
		posicao.append(-1)
		for i in range(1, len(azimute_adm)):
			if (round(azimute_adm[i],2) != round(azimute_adm[i-1],2) or round(dip_adm[i],2) != round(dip_adm[i-1],2)):
				posicao.append(i-1)	
		posicao.append(len(azimute_adm)-1)
		
		azimutes = []
		dips = []
		lags =[]
		continuidades =[]
		paresv =[]

		for i in range(1,len(posicao)):
			azimutes.append(azimute_adm[posicao[i-1]+1:posicao[i]])
			dips.append(dip_adm[posicao[i-1]+1:posicao[i]])
			lags.append(lag_adm[posicao[i-1]+1:posicao[i]])
			continuidades.append(continuidade[posicao[i-1]+1:posicao[i]])
			paresv.append(pares[posicao[i-1]+1:posicao[i]])

		# Write hml file for experimental variograms

		save2= open(save2,"w")
		save2.write("    <experimental_variograms> \n")

		for i in range(0, len(azimutes)):
			azim = []
			Dip =[]
			lagv =[]
			cont =[]
			par =[]
			azim = azimutes[i]
			Dip = dips[i]
			lagv = lags[i]
			cont =continuidades[i]
			par = paresv[i]
			save2.write("  <variogram> \n")
			save2.write("  <title>variogram -azth="+str(round(azim[0],2))+", dip="+str(round(Dip[0],2))+"</title> \n")
			direction1 = math.sin(Dip[0])*math.cos(azim[0])
			direction2 = math.sin(Dip[0])*math.sin(azim[0])
			direction3 = -math.sin(Dip[0])
			save2.write("<direction>" +str(direction1) + " " + str(direction2) +" "+ str(direction3)+ "</direction> \n")
			save2.write("   <x>")
			for j in range(0,len(lagv)):
				save2.write(str(lagv[j]) + " ")
			save2.write("</x> \n")
			save2.write("   <y>")
			for p in range(0,len(cont)):
				save2.write(str(cont[p])+ " ")
			save2.write("</y> \n")
			save2.write("   <pairs>")
			for h in range(0,len(cont)):
				save2.write(str(par[h])+ " ")
			save2.write("</pairs> \n")
			save2.write("  </variogram> \n")
		save2.write("   </experimental_variograms> \n")
		save2.close()	
			
				
	
	print("Finish")
			
    	return True 
Example #12
0
    def execute(self):
        '''# Execute the funtion read_params
        read_params(self.params)
        print self.params'''

        #Get the grid and rock type propery
        grid = self.params['propertyselectornoregion']['grid']
        prop = self.params['propertyselectornoregion']['property']

        #Get the X, Y and Z coordinates and RT property
        X = sgems.get_property(grid, '_X_')
        Y = sgems.get_property(grid, '_Y_')
        Z = sgems.get_property(grid, '_Z_')
        RT_data = sgems.get_property(grid, prop)

        # Getting properties
        grid_krig = self.params['gridselectorbasic_2']['value']
        grid_var = self.params['gridselectorbasic']['value']
        props = (self.params['orderedpropertyselector']['value']).split(';')
        n_var = int(self.params['indicator_regionalization_input']
                    ['number_of_indicator_group'])
        n_prop = int(self.params['orderedpropertyselector']['count'])
        min_cond = self.params['spinBox_2']['value']
        max_cond = self.params['spinBox']['value']

        # Error messages
        if len(grid_var) == 0 or len(grid_krig) == 0:
            print 'Select the variables'
            return False

        if n_var != n_prop:
            print 'Number of variables and number of variograms models are diferent.'
            return False

        #Creating an empty list to store the interpolated distances
        SG_OK_list = []

        # Loop in every variable
        for i in xrange(0, n_var):

            # Getting variables
            prop_HD = props[i]
            prop_name = "Interpolated_" + str(prop_HD)
            prop_name_var = "Interpolated_" + str(prop_HD) + ' krig_var'
            var_str = ''
            indicator_group = "Indicator_group_" + str(i + 1)
            elipsoide = self.params['ellipsoidinput']['value']
            n_struct = int(
                self.params['indicator_regionalization_input'][indicator_group]
                ['Covariance_input']['structures_count'])

            # Error message
            if n_struct == 0:
                print 'Variogram have no structures'
                return False

            # Loop in every variogram structure
            for j in xrange(0, n_struct):
                # Getting variogram parameters
                Structure = "Structure_" + str(j + 1)

                cov_type = self.params['indicator_regionalization_input'][
                    indicator_group]['Covariance_input'][Structure][
                        'Two_point_model']['type']

                cont = self.params['indicator_regionalization_input'][
                    indicator_group]['Covariance_input'][Structure][
                        'Two_point_model']['contribution']

                if cov_type == 'Nugget Covariance':
                    #Writing variogram parameters on a variable in nugget effect case
                    var_str = var_str + '<{} type="{}">  <Two_point_model  contribution="{}"  type="{}"   >    </Two_point_model>    </Structure_1> '.format(
                        Structure, 'Covariance', cont, cov_type, Structure)

                else:
                    range1 = self.params['indicator_regionalization_input'][
                        indicator_group]['Covariance_input'][Structure][
                            'Two_point_model']['ranges']['range1']
                    range2 = self.params['indicator_regionalization_input'][
                        indicator_group]['Covariance_input'][Structure][
                            'Two_point_model']['ranges']['range2']
                    range3 = self.params['indicator_regionalization_input'][
                        indicator_group]['Covariance_input'][Structure][
                            'Two_point_model']['ranges']['range3']

                    rake = self.params['indicator_regionalization_input'][
                        indicator_group]['Covariance_input'][Structure][
                            'Two_point_model']['angles']['rake']
                    dip = self.params['indicator_regionalization_input'][
                        indicator_group]['Covariance_input'][Structure][
                            'Two_point_model']['angles']['dip']
                    azimuth = self.params['indicator_regionalization_input'][
                        indicator_group]['Covariance_input'][Structure][
                            'Two_point_model']['angles']['azimuth']

                    # Writing variogram parameters on a variable in other cases
                    var_str = var_str + '<{} type="{}">  <Two_point_model  contribution="{}"  type="{}"   >      <ranges range1="{}"  range2="{}"  range3="{}"   />      <angles azimuth="{}"  dip="{}"  rake="{}"   />    </Two_point_model>    </{}> '.format(
                        Structure, 'Covariance', cont, cov_type, range1,
                        range2, range3, azimuth, dip, rake, Structure)

            # Calling ordinary kriging for each variable, using the variograms parameters above
            sgems.execute(
                'RunGeostatAlgorithm  kriging::/GeostatParamUtils/XML::<parameters>  <algorithm name="kriging" />     <Variogram  structures_count="{}" >    {}  </Variogram>    <ouput_kriging_variance  value="1"  />     <output_n_samples_  value="0"  />     <output_average_distance  value="0"  />     <output_sum_weights  value="0"  />     <output_sum_positive_weights  value="0"  />     <output_lagrangian  value="0"  />     <Nb_processors  value="-2"  />    <Grid_Name value="{}" region=""  />     <Property_Name  value="{}" />     <Hard_Data  grid="{}"   property="{}"   region=""  />     <Kriging_Type  type="Ordinary Kriging (OK)" >    <parameters />  </Kriging_Type>    <do_block_kriging  value="1"  />     <npoints_x  value="5" />     <npoints_y  value="5" />     <npoints_z  value="5" />     <Min_Conditioning_Data  value="{}" />     <Max_Conditioning_Data  value="{}" />     <Search_Ellipsoid  value="{}" />    <AdvancedSearch  use_advanced_search="0"></AdvancedSearch>  </parameters>'
                .format(n_struct, var_str, grid_krig, prop_name, grid_var,
                        prop_HD, min_cond, max_cond, elipsoide))

            SG_OK_list.append(sgems.get_property(grid_krig, prop_name))

            #Deleting kriged distances
            sgems.execute('DeleteObjectProperties  {}::{}'.format(
                grid_krig, prop_name))
            sgems.execute('DeleteObjectProperties  {}::{}'.format(
                grid_krig, prop_name_var))

        RT = (self.params['orderedpropertyselector']['value']).split(';')

        #Determinig geomodel based on minimum estimed signed distance function
        GeoModel = SG_OK_list[0][:]

        t = 0
        for i in range(len(SG_OK_list[0])):
            sgmin = 10e21
            for j in range(len(SG_OK_list)):
                if SG_OK_list[j][i] < sgmin:
                    sgmin = SG_OK_list[j][i]
                    t = j
            if math.isnan(SG_OK_list[j][i]):
                GeoModel[i] = float('nan')
            else:
                GeoModel[i] = (int(RT[t].split('RT_')[-1]))

        #Creating GeoModel property
        lst_props_grid = sgems.get_property_list(grid_krig)
        prop_final_data_name = 'Geologic_Model'

        if (prop_final_data_name in lst_props_grid):
            flag = 0
            i = 1
            while (flag == 0):
                test_name = prop_final_data_name + '-' + str(i)
                if (test_name not in lst_props_grid):
                    flag = 1
                    prop_final_data_name = test_name
                i = i + 1

        #Assign conditioning data to grid node
        for i in range(len(RT_data)):
            if not math.isnan(RT_data[i]):
                closest_node = sgems.get_closest_nodeid(
                    grid_krig, X[i], Y[i], Z[i])
                GeoModel[closest_node] = RT_data[i]

        sgems.set_property(grid_krig, prop_final_data_name, GeoModel)

        #Operating softmax transformation
        if self.params['softmax_check']['value'] == '1':

            gamma = float(self.params['Gamma']['value'])
            Prob_list = SG_OK_list[:]

            for i in range(len(SG_OK_list[0])):
                soma = 0
                for j in range(len(SG_OK_list)):
                    soma = soma + math.exp(-SG_OK_list[j][i] / gamma)
                for j in range(len(SG_OK_list)):
                    Prob_list[j][i] = math.exp(
                        -SG_OK_list[j][i] / gamma) / soma

            #Creating probabilities propreties
            for k in range(len(Prob_list)):
                prop_final_data_name = 'Probability_RT' + str(
                    RT[k].split('RT_')[-1])

                if (prop_final_data_name in lst_props_grid):
                    flag = 0
                    i = 1
                    while (flag == 0):
                        test_name = prop_final_data_name + '-' + str(i)
                        if (test_name not in lst_props_grid):
                            flag = 1
                            prop_final_data_name = test_name
                        i = i + 1

                sgems.set_property(grid_krig, prop_final_data_name,
                                   Prob_list[k])

            #Operating servo-system
            if self.params['servo_check']['value'] == '1':
                var_rt_grid = self.params['targe_prop']['grid']
                var_rt_st = self.params['targe_prop']['property']
                var_rt_region = self.params['targe_prop']['region']
                if len(var_rt_grid) == 0 or len(var_rt_st) == 0:
                    print 'Select the target proportion property'
                    return False

                #Getting variables
                var_rt = sgems.get_property(var_rt_grid, var_rt_st)

                #Getting parameters
                lambda1 = float(self.params['Lambda']['value'])
                mi = lambda1 / (1 - lambda1)

                #Checking if a region exist
                if len(var_rt_region) == 0:
                    #Variable without a region
                    var_region = var_rt

                else:
                    region_rt = sgems.get_region(var_rt_grid, var_rt_region)
                    #Geting the variable inside the region
                    var_region = []
                    for i in range(len(var_rt)):
                        if region_rt[i] == 1:
                            var_region.append(var_rt[i])

                #Getting the target proportion
                target_prop = proportion(var_region, RT)

                #Getting the random path
                ran_path = random_path(Prob_list[0])

                #Removing the blocks outside the region from randon path
                if len(var_rt_region) != 0:
                    for i in range(len(region_rt)):
                        if region_rt[i] == 0:
                            ran_path.remove(i)

                #servo system
                p = 0
                GeoModel_corrected = GeoModel[:]

                visited_rts = []
                for j in ran_path:
                    visited_rts.append(GeoModel[j])
                    instant_proportions = proportion(visited_rts, RT)

                    sgmax = 10e-21
                    for i in range(len(Prob_list)):
                        Prob_list[i][j] = Prob_list[i][j] + (
                            mi * (target_prop[i] - instant_proportions[i]))
                        if Prob_list[i][j] > sgmax:
                            sgmax = Prob_list[i][j]
                            p = i

                    GeoModel_corrected[j] = int(RT[p][-1])
                    visited_rts[-1] = int(RT[p].split('RT_')[-1])

                #Correcting servo servo-system by the biggest proportion on a neighborhood
                GeoModel_corrected_servo_prop = GeoModel_corrected[:]
                ran_path_servo_correction = random_path(
                    GeoModel_corrected_servo_prop)
                for i in ran_path_servo_correction:
                    vizinhanca = neighb(grid_krig, i)

                    blk_geo_model_corrected_servo = []
                    for j in vizinhanca:
                        blk_geo_model_corrected_servo.append(
                            GeoModel_corrected_servo_prop[j])

                    proportions_servo = proportion(
                        blk_geo_model_corrected_servo, RT)
                    indice_max_prop = proportions_servo.index(
                        max(proportions_servo))

                    GeoModel_corrected_servo_prop[i] = int(
                        RT[indice_max_prop].split('RT_')[-1])

                #Creating Geologic_Model_Servo_System property
                prop_final_data_name = 'Geologic_Model_Servo_System'

                if (prop_final_data_name in lst_props_grid):
                    flag = 0
                    i = 1
                    while (flag == 0):
                        test_name = prop_final_data_name + '-' + str(i)
                        if (test_name not in lst_props_grid):
                            flag = 1
                            prop_final_data_name = test_name
                        i = i + 1

                #Creating Geologic_Model_Corrected property
                prop_final_data_name1 = 'Geologic_Model_Corrected'

                if (prop_final_data_name1 in lst_props_grid):
                    flag = 0
                    i = 1
                    while (flag == 0):
                        test_name1 = prop_final_data_name1 + '-' + str(i)
                        if (test_name1 not in lst_props_grid):
                            flag = 1
                            prop_final_data_name1 = test_name1
                        i = i + 1

                #Assign conditioning data to grid node
                for i in range(len(RT_data)):
                    if not math.isnan(RT_data[i]):
                        closest_node = sgems.get_closest_nodeid(
                            grid_krig, X[i], Y[i], Z[i])
                        GeoModel_corrected[closest_node] = RT_data[i]
                        GeoModel_corrected_servo_prop[closest_node] = RT_data[
                            i]

                #Setting properties
                sgems.set_property(grid_krig, prop_final_data_name,
                                   GeoModel_corrected)
                sgems.set_property(grid_krig, prop_final_data_name1,
                                   GeoModel_corrected_servo_prop)

        return True
    def execute(self):
	print self.params
	# ESTABELECA OS PARAMETROS INICIAIS
	head_property= self.params['head_prop']['property']
	head_grid = self.params['head_prop']['grid']
	tail_property = self.params['tail_prop']['property']
	tail_grid= self.params['tail_prop']['grid']
	C_variogram = int(self.params['C_variogram']['value'])
	C_covariance= int(self.params['C_covariance']['value'])
	nlags= int(self.params['nlags']['value'])
	lagdistance = float(self.params['lagdistance']['value'])
	lineartolerance= float(self.params['lineartolerance']['value'])
	htolerance = float(self.params['htolangular']['value'])
	vtolerance = float(self.params['vtolangular']['value'])
	hband = float(self.params['hband']['value'])
	vband = float(self.params['vband']['value'])
	dip = float(self.params['Dip']['value'])
	azimute = float(self.params['Azimute']['value'])
	gdiscrete = int(self.params['Gdiscrete']['value'])
	ncontour = int(self.params['ncontour']['value'])
	Remove = float(self.params['Remove']['value'])	

	def retire_nan (x,y,z,v):
		xn =[]
		yn =[]
		zn =[]
		vn =[]
		for i in range(0,len(v)):
			if (v[i] > -99999999999999999):
				
				xn.append(x[i])
				yn.append(y[i])
				zn.append(z[i])
				vn.append(v[i])
		return xn, yn, zn, vn
			


	xh = []
	yh = []
	zh = [] 
	vh = []
	
	xh1 = sgems.get_property(head_grid, "_X_")
	yh1 = sgems.get_property(head_grid, "_Y_")
	zh1 = sgems.get_property(head_grid, "_Z_")
	vh1 = sgems.get_property(head_grid, head_property)	

	xh, yh, zh, vh = retire_nan(xh1,yh1,zh1,vh1)


	xt = []
	yt = []
	zt = []	
	vt = []

	xt1 = sgems.get_property(tail_grid, "_X_")
	yt1 = sgems.get_property(tail_grid, "_Y_")
	zt1 = sgems.get_property(tail_grid, "_Z_")
	vt1 = sgems.get_property(tail_grid, tail_property)

	xt, yt, zt, vt = retire_nan(xt1,yt1,zt1,vt1)		

	# VERIFIQUE O NUMERO DE DIMENSOES DO PROBLEMA
	
	# VERIFICACAO DAS DIMENSOES DO HEAD

	cdimensaoxh = False
	cdimensaoyh = False
	cdimensaozh = False

	for x in range(0,len(xh)):
		if (xh[x] != 0):
			cdimensaoxh = True


	for y in range(0,len(yh)):
		if (yh[y] != 0):
			cdimensaoyh = True


	for z in range(0,len(zh)):
		if (zh[z] != 0):
			cdimensaozh = True

	# VERIFICACAO DAS DIMENSOES DO TAIL

	cdimensaoxt = False
	cdimensaoyt = False
	cdimensaozt = False

	for x in range(0,len(xt)):
		if (xt[x] != 0):
			cdimensaoxt = True

	for y in range(0,len(yt)):
		if (yt[y] != 0):
			cdimensaoyt = True


	for z in range(0,len(zt)):
		if (zt[z] != 0):
			cdimensaozt = True

	if ((cdimensaoxt == cdimensaoxh) and (cdimensaoyt == cdimensaoyh) and (cdimensaozt == cdimensaozh)):
		


		# DEFINA A MAXIMA DISTANCIA PERMISSIVEL
		
		dmaximo = (nlags + 0.5)*lagdistance
		
		#CONVERTA TOLERANCIAS SE ELAS FOREM IGUAIS A ZERO 
		if (htolerance == 0):
			htolerance= 45
		if (vtolerance == 0):
			vtolerance = 45
		if (hband == 0):
			hband = lagdistance/2
		if (vband == 0):
			vband = lagdistance/2
		if (lagdistance == 0):		
			lagdistance = 100
		if (lineartolerance == 0):
			lineartolerance = lagdistance/2
		
		
		
	
		#CONVERTA OS VALORES DE TOLERANCIA EM RADIANOS
		htolerance = math.radians(htolerance)
		vtolerance = math.radians(vtolerance)	

		# DETERMINE AS PROJECOES DO DIP E DO AZIMUTE 
		htolerance = math.cos(htolerance)
		vtolerance = math.cos(vtolerance)

		
		xhrot =[]
		yhrot =[]
		zhrot =[]
		xttrot =[]
		yttrot=[]
		zttrot=[]		
		
		for i in range(0, len(xh)):

		    # ROTACIONE PRIMEIRAMENTE NO AZIMUTE

		    xrot = math.cos(math.radians(azimute))*xh[i] - math.sin(math.radians(azimute))*yh[i]
		    yrot = math.sin(math.radians(azimute))*xh[i] + math.cos(math.radians(azimute))*yh[i]
		    yrot2 = math.cos(math.radians(dip))*yrot - math.sin(math.radians(dip))*zh[i]
		    zrot = math.sin(math.radians(dip))*yrot + math.cos(math.radians(dip))*zh[i]

		    xhrot.append(xrot)
		    yhrot.append(yrot2)
		    zhrot.append(zrot)

		    # ROTACIONE EM SEGUIDA NO MERGULHO

		    xtrot = math.cos(math.radians(azimute))*xt[i] - math.sin(math.radians(azimute))*yt[i]
		    ytrot = math.sin(math.radians(azimute))*xt[i] + math.cos(math.radians(azimute))*yt[i]
		    ytrot2 = math.cos(math.radians(dip))*ytrot - math.sin(math.radians(dip))*zt[i]
		    ztrot = math.sin(math.radians(dip))*ytrot + math.cos(math.radians(dip))*zt[i]

		    xttrot.append(xtrot)
		    yttrot.append(ytrot2)
		    zttrot.append(ztrot)


		#CONVERTA OS VALORES DE TOLERANCIA EM RADIANOS
		htolerance = math.radians(htolerance)
		vtolerance = math.radians(vtolerance)

		# DETERMINE AS PROJECOES DO DIP E DO AZIMUTE
		htolerance = math.cos(htolerance)
		vtolerance = math.cos(vtolerance)

		# DEFINA TODAS AS DISTANCIAS EUCLIDIANAS POSSIVEIS

		cabeca = []
		rabo = []
		cabeca2 =[]
		rabo2 =[]
		distanciah =[]
		distanciaxy =[]
		distanciax =[]
		distanciay = []
		distanciaz = []
		for t in range(0, len(yt)):
		    for h in range(t, len(yh)):
					
			
			dx = xhrot[h]-xttrot[t]
			dy= yhrot[h]-yttrot[t]
			dz = zhrot[h]-zttrot[t]
			dh = math.sqrt(math.pow(dy,2) + math.pow(dx,2) + math.pow(dz,2))
			
			if (dh <dmaximo):
				cabeca.append(vh[h])
				cabeca2.append(vt[h])
				rabo2.append(vt[t])
				rabo.append(vh[t])
			
				distanciay.append(dy)
				distanciax.append(dx)
				distanciaz.append(dz)
				distanciah.append(dh)
				distanciaxy.append(math.sqrt(math.pow(dy,2) + math.pow(dx,2)))
		
		# CALCULE TODOS OS VALORES DE COS E SENO ADMISSIVEIS AO AZIMUTE		
		

		cos_Azimute = []
		sin_Azimute = []
		flutuante_d = 0
		
		
		for a in range(0,360,20):
			diferenca = a 
			cos_Azimute.append(math.cos(math.radians(90-diferenca)))
			sin_Azimute.append(math.sin(math.radians(90-diferenca)))
			cos_Dip = math.cos(math.radians(90))
			sin_Dip = math.sin(math.radians(90))
	
		distancias_admissiveis = []
		azimute_admissiveis = []
		dip_admissiveis =[]
		v_valores_admissiveis_h =[]
		v_valores_admissiveis_t =[]
		v_valores_admissiveis_h2 =[]
		v_valores_admissiveis_t2 =[]
		pares = []		

		

		# CALCULE OS PONTOS ADMISSIVEIS 
		for a in xrange(0,18):	
			# reestabelca o valor do norte retirando novamente o azimute
			azm = math.radians(a*20)
			for l in xrange(0, nlags):			
				valores_admissiveis_h = []
				valores_admissiveis_t = []
				valores_admissiveis_h2 =[]
				valores_admissiveis_t2 =[]
				distancia_admissivel = []
				azimute_admissivel =[]
				dip_admissivel=[]
				lag= lagdistance*(l+1)
				par= 0 
				limitemin = lag - lineartolerance
				limitemax = lag + lineartolerance
				for p in xrange(0,len(distanciah)):	
					if (distanciah[p] > limitemin and distanciah[p] < limitemax):						
						if (distanciaxy[p] > 0.000): 				
							check_azimute = (distanciax[p]*cos_Azimute[a] +distanciay[p]*sin_Azimute[a])/distanciaxy[p]
						else:
							check_azimute = 1
						check_azimute = math.fabs(check_azimute)
						if (check_azimute >= htolerance):								
							check_bandh = (cos_Azimute[a]*distanciay[p]) - (sin_Azimute[a]*distanciax[p])
							check_bandh = math.fabs(check_bandh)
							if (check_bandh < hband):								
								if(distanciah[p] > 0.000):
									check_dip = (math.fabs(distanciaxy[p])*sin_Dip + distanciaz[p]*cos_Dip)/distanciah[p]
								else:
									check_dip = 0.000
								check_dip = math.fabs(check_dip) 
								if (check_dip >= vtolerance):
									check_bandv = sin_Dip*distanciaz[p] - cos_Dip*math.fabs(distanciaxy[p])
									check_bandv = math.fabs(check_bandv)
									if (check_bandv < vband):
											valores_admissiveis_h.append(cabeca[p])
											valores_admissiveis_t.append(rabo[p])
											valores_admissiveis_h2.append(cabeca2[p])
											valores_admissiveis_t2.append(rabo2[p])
											distancia_admissivel.append(distanciah[p])
											par = par + 1	
											azimute_admissivel.append(azm)							
				if (len(valores_admissiveis_h) > 0 and len(valores_admissiveis_t) > 0):	
					if (par > 0):		
						v_valores_admissiveis_h.append(valores_admissiveis_h)
						v_valores_admissiveis_h2.append(valores_admissiveis_h2)
						v_valores_admissiveis_t2.append(valores_admissiveis_t2)
						v_valores_admissiveis_t.append(valores_admissiveis_t)
						distancias_admissiveis.append(distancia_admissivel)
						pares.append(par)
						azimute_admissiveis.append(azimute_admissivel)	
		

		# CALCULE AS FUNCOES DE CONTINUIDADE ESPACIAL SEGUNDO OS VALORES ADMISSIVEIS	

		# CALCULE O VARIOGRAMA 
		
		if (C_variogram == 1): 		
			continuidade =[]
			lag_adm =[]
			azimute_adm =[]
			for i in xrange(0,len(v_valores_admissiveis_h)):
				flutuantet =[]
				flutuanteh =[]
				flutuanteh2 = []
				flutuantet2 =[]
				flutuanted =[]
				flutuantea=[]
				flutuantedip=[]
				par_var = 0
				flutuanteh = v_valores_admissiveis_h[i][:]
				flutuanteh2= v_valores_admissiveis_h2[i][:]
				flutuantet = v_valores_admissiveis_t[i][:]
				flutuantet2 = v_valores_admissiveis_t2[i][:]
				flutuanted = distancias_admissiveis[i][:]
				flutuantea= azimute_admissiveis[i][:]
				par_var= pares[i]
				soma = 0
				lagmedio =0
				agmedio =0 
				dgmedio = 0
				for j in xrange(0, len(flutuanteh)):
					soma = soma + (flutuanteh[j] - flutuantet[j])*(flutuanteh2[j]-flutuantet2[j])/(2*pares[i])
				for z in xrange(0, len(flutuanted)):
					lagmedio = lagmedio + flutuanted[z]/len(flutuanted)
				for g in xrange(0, len(flutuantea)):
					agmedio = agmedio + flutuantea[g]/len(flutuantea)
				if (soma <= Remove):
					continuidade.append(soma)
					azimute_adm.append(agmedio)
					lag_adm.append(lagmedio)

		# CALCULE O COVARIOGRAMA 
		if (C_covariance == 1): 		
			continuidade =[]
			lag_adm =[]
			azimute_adm =[]
			for i in xrange(0,len(v_valores_admissiveis_h)):
				flutuantet =[]
				flutuanteh =[]
				flutuanted =[]
				flutuantea=[]
				par_var = 0
				flutuanteh = v_valores_admissiveis_h[i]
				flutuantet = v_valores_admissiveis_t[i]
				flutuanted = distancias_admissiveis[i]
				flutuantea= azimute_admissiveis[i]
				par_var= pares[i]
				soma = 0
				lagmedio =0
				agmedio =0 
				dgmedio = 0
				somah = 0
				somat = 0 
				mediah = 0
				mediat =0
				for d in range (0, len(flutuanteh)):
					somah = somah + flutuanteh[d]
				mediah = float(somah/len(flutuanteh))
				for t in range (0, len(flutuantet)):
					somat = somat + flutuantet[t]
				mediat = float(somat/len(flutuantet))
				for j in xrange(0, len(flutuanteh)):		
						soma = soma + float(((flutuanteh[j] - mediah)*(flutuantet[j] - mediat))/(par_var))
				for z in xrange(0, len(flutuanted)):
					lagmedio = lagmedio + flutuanted[z]/len(flutuanted)
				for g in xrange(0, len(flutuantea)):
					agmedio = agmedio + flutuantea[g]/len(flutuantea)
				if (soma <= Remove):				
					continuidade.append(soma)
					azimute_adm.append(agmedio)
					lag_adm.append(lagmedio)
		print ("OK")
	
		# RECORD FILE 

		
		arquivo2 = open("saida_varmap.txt","w")
		arquivo2.write(str(gdiscrete)+"\n")
		arquivo2.write(str(ncontour)+"\n")
		for i in range(0, len(azimute_adm)):
			arquivo2.write(str(azimute_adm[i])+"	"+str(lag_adm[i])+ "	"+str(continuidade[i]) + "\n")
		arquivo2.close()


		# PLOTE O MAPA DE VARIOGRAMAS INTERPOLADO
		
		os.system("python plot_varmap.py")
Example #14
0
import sgems
sgems.execute('LoadObjectFromFile  D:/Users/jwhite/Projects/Broward/Geostats/SGEMS/Layer1_thk.sgems::s-gems')
data = sgems.get_property('Layer_Thk','Layer_1_thk NGVD_meters')
print data
Example #15
0
"""
Simple way to export SGeMS data to Paraview;
Need to install python module pyevtk;
In this file, data is exported as structured grid to be visulized at Paraview
The output file goes to SGeMS main folder as '.vtu'
"""

from pyevtk.hl import gridToVTK
import numpy as np
import sgems

# Parameters (NEED TO INPUT grid name and property name)
g = "grid1"
p = "30strike"

prop = sgems.get_property(g, p)

# Grid parameters (NEED TO INPUT lx, ly and lz as the dimensions of the grid)
nd = sgems.get_dims(g)
ox, oy, oz = 0.0, 0.0, 0.0
lx, ly, lz = 260.0, 300.0, 1.0
dx, dy, dz = lx / nd[0], ly / nd[1], lz / nd[2]
ncells = nd[0] * nd[1] * nd[2]
npoints = (nd[0] + 1) * (nd[1] + 1) * (nd[2] + 1)

# Coordinates
x = np.arange(ox, ox + lx + 0.1 * dx, dx, dtype='float64')
y = np.arange(oy, oy + ly + 0.1 * dy, dy, dtype='float64')
z = np.arange(oz, oz + lz + 0.1 * dz, dz, dtype='float64')

# Writing output
Example #16
0
    def execute(self):

        #aqui vai o codigo
        #getting variables
        var_type = self.params['comboBox']['value']
        tg_grid_name = self.params['gridselector']['value']
        tg_region_name = self.params['gridselector']['region']
        tg_prop_name = self.params['lineEdit']['value']
        keep_variables = self.params['checkBox_2']['value']
        props_grid_name = self.params['gridselectorbasic']['value']
        var_names = self.params['orderedpropertyselector']['value'].split(';')
        codes = [v.split('_')[-1] for v in var_names]

        #getting variograms
        print('Getting variogram models')

        variables = []
        nan_filters = []
        for v in var_names:
            values = np.array(sgems.get_property(props_grid_name, v))
            nan_filter = np.isfinite(values)
            filtered_values = values[nan_filter]
            nan_filters.append(nan_filter)
            variables.append(filtered_values)
        nan_filter = np.product(nan_filters, axis=0)
        nan_filter = nan_filter == 1

        x, y, z = np.array(sgems.get_X(props_grid_name))[nan_filter], np.array(
            sgems.get_Y(props_grid_name))[nan_filter], np.array(
                sgems.get_Z(props_grid_name))[nan_filter]

        use_model_file = self.params['checkBox']['value']
        if use_model_file == '1':
            path = self.params['filechooser']['value']
            variograms = helpers.modelfile_to_ar2gasmodel(path)
            if len(variograms) == 1:
                values_covs = list(variograms.values())
                varg_lst = values_covs * len(codes)
                variograms = {}
                variograms[0] = varg_lst[0]
        else:
            p = self.params
            varg_lst = helpers.ar2gemsvarwidget_to_ar2gascovariance(p)
            if len(varg_lst) == 0:
                variograms = {}
            if len(varg_lst) == 1:
                varg_lst = varg_lst * len(codes)
                variograms = {}
                variograms[0] = varg_lst[0]

            else:
                variograms = dict(zip(codes, varg_lst))

        #interpolating variables
        a2g_grid = helpers.ar2gemsgrid_to_ar2gasgrid(tg_grid_name,
                                                     tg_region_name)

        interpolated_variables = interpolate_variables(
            x, y, z, variables, codes, a2g_grid, variograms, keep_variables,
            var_type, tg_prop_name, tg_grid_name)

        #creating a geologic model
        geomodel = build_geomodel(var_type, interpolated_variables, codes,
                                  a2g_grid, tg_grid_name, tg_prop_name)

        #Refining model
        iterations = int(self.params['iterations']['value'])
        fx, fy, fz = int(self.params['fx']['value']), int(
            self.params['fy']['value']), int(self.params['fz']['value'])

        if iterations > 0:

            if len(variables) == 1:
                print(
                    'Sorry! Refinemnt works only for multicategorical models.')
                return False

            grid = a2g_grid
            geomodel = geomodel
            if tg_region_name != '':
                region = sgems.get_region(tg_grid_name, tg_region_name)

            for i in range(iterations):
                print('Refinemnt iteration {}'.format(i + 1))
                print('Defining refinment zone...')
                ref_zone, indices = refinement_zone(grid, geomodel)

                if tg_region_name != '':
                    downscaled_grid, downscaled_props = helpers.downscale_properties(
                        grid, [ref_zone, geomodel,
                               np.array(region)], fx, fy, fz)
                    region = downscaled_props[2]
                    m1 = np.array(downscaled_props[0] == -999)
                    m2 = np.array(downscaled_props[2] == 1)
                    mask = m1 * m2
                    mask = np.where(mask == 1, True, False).tolist()
                    nx, ny, nz = downscaled_grid.dim()[0], downscaled_grid.dim(
                    )[1], downscaled_grid.dim()[2]
                    sx, sy, sz = downscaled_grid.cell_size(
                    )[0], downscaled_grid.cell_size(
                    )[1], downscaled_grid.cell_size()[2]
                    ox, oy, oz = downscaled_grid.origin(
                    )[0], downscaled_grid.origin()[1], downscaled_grid.origin(
                    )[2]
                    downscaled_grid = ar2gas.data.CartesianGrid(
                        nx, ny, nz, sx, sy, sz, ox, oy, oz)
                else:
                    downscaled_grid, downscaled_props = helpers.downscale_properties(
                        grid, [ref_zone, geomodel], fx, fy, fz)
                    mask = downscaled_props[0] == -999
                grid = downscaled_grid
                grid_name = tg_grid_name + '_' + tg_prop_name + '_iteration_{}'.format(
                    i + 1)
                helpers.ar2gasgrid_to_ar2gems(grid_name, grid)

                masked_grid = ar2gas.data.MaskedGrid(downscaled_grid, mask)

                interpolated_variables = interpolate_variables(
                    x, y, z, variables, codes, masked_grid, variograms,
                    keep_variables, var_type, tg_prop_name, grid_name)

                geomodel = build_refined_geomodel(interpolated_variables,
                                                  downscaled_props, codes,
                                                  var_type)

            sgems.set_property(grid_name, tg_prop_name, geomodel)
            print('Finished!')

        return True
Example #17
0
    def execute(self):

        #aqui vai o codigo
        #getting variables
        tg_grid_name = self.params['gridselector']['value']
        tg_region_name = self.params['gridselector']['region']
        tg_prop_name = self.params['lineEdit']['value']
        keep_variables = self.params['checkBox_2']['value']
        props_grid_name = self.params['gridselectorbasic']['value']
        var_names = self.params['orderedpropertyselector']['value'].split(';')
        codes = [v.split('_')[-1] for v in var_names]

        dcf_param = self.params['comboBox_2']['value']
        f_min_o = float(self.params['doubleSpinBox']['value'])
        f_min_p = float(self.params['doubleSpinBox_2']['value'])

        acceptance = [
            float(i) for i in self.params['lineEdit_9']['value'].split(',')
        ]
        if len(acceptance) == 1 and len(codes) > 1:
            acceptance = acceptance * len(codes)
        acceptance = np.array(acceptance)

        #kernels variables
        function = self.params['comboBox']['value']
        supports = [
            float(i) for i in self.params['lineEdit_5']['value'].split(',')
        ]
        azms = [
            float(i) for i in self.params['lineEdit_2']['value'].split(',')
        ]
        dips = [
            float(i) for i in self.params['lineEdit_3']['value'].split(',')
        ]
        rakes = [
            float(i) for i in self.params['lineEdit_4']['value'].split(',')
        ]
        nuggets = [
            float(i) for i in self.params['lineEdit_6']['value'].split(',')
        ]
        major_med = [
            float(i) for i in self.params['lineEdit_7']['value'].split(',')
        ]
        major_min = [
            float(i) for i in self.params['lineEdit_8']['value'].split(',')
        ]

        kernels_par = {
            'supports': supports,
            'azms': azms,
            'dips': dips,
            'rakes': rakes,
            'nuggets': nuggets,
            'major_meds': major_med,
            'major_mins': major_min
        }

        for key in kernels_par:
            if len(kernels_par[key]) == 1 and len(codes) > 1:
                kernels_par[key] = kernels_par[key] * len(codes)

        kernels_par['function'] = [function] * len(codes)

        print(kernels_par)

        #getting coordinates
        variables = []
        nan_filters = []
        for v in var_names:
            values = np.array(sgems.get_property(props_grid_name, v))
            nan_filter = np.isfinite(values)
            filtered_values = values[nan_filter]
            nan_filters.append(nan_filter)
            variables.append(filtered_values)
        nan_filter = np.product(nan_filters, axis=0)
        nan_filter = nan_filter == 1

        x, y, z = np.array(sgems.get_X(props_grid_name))[nan_filter], np.array(
            sgems.get_Y(props_grid_name))[nan_filter], np.array(
                sgems.get_Z(props_grid_name))[nan_filter]

        #Interpolating variables
        a2g_grid = helpers.ar2gemsgrid_to_ar2gasgrid(tg_grid_name,
                                                     tg_region_name)
        print('Computing results by RBF using a {} kernel...'.format(function))
        interpolated_variables = {}

        for idx, v in enumerate(variables):
            rt = int(codes[idx])
            interpolated_variables[rt] = {}
            print('Interpolating RT {}'.format(rt))

            if kernels_par['supports'][idx] == 0:
                mask = v < 0
                kernels_par['supports'][idx] = helpers.max_dist(
                    x, y, z, mask, a2g_grid)
                print('Estimated support is {}'.format(
                    kernels_par['supports'][idx]))

            rbf = RBF(x,
                      y,
                      z,
                      v,
                      function=kernels_par['function'][idx],
                      nugget=kernels_par['nuggets'][idx],
                      support=kernels_par['supports'][idx],
                      major_med=kernels_par['major_meds'][idx],
                      major_min=kernels_par['major_mins'][idx],
                      azimuth=kernels_par['azms'][idx],
                      dip=kernels_par['dips'][idx],
                      rake=kernels_par['rakes'][idx])

            dc_param = dc_parametrization(v, dcf_param, f_min_o, f_min_p)
            for t in dc_param:
                print('Working on {}...'.format(t))

                rbf.train(dc_param[t])
                results = rbf.predict(a2g_grid)
                interpolated_variables[rt][t] = results

                if keep_variables == '1':
                    prop_name = 'interpolated_' + tg_prop_name + '_' + dcf_param + '_' + t + '_' + str(
                        rt)
                    sgems.set_property(tg_grid_name, prop_name,
                                       results.tolist())

        print('Done!')

        #Generating geological models
        print('Building geomodel...')
        #getting closest node to each sample
        ids = [
            sgems.get_closest_nodeid(tg_grid_name, xi, yi, zi)
            for xi, yi, zi in zip(x, y, z)
        ]
        rt_prop = sd_to_cat(variables, codes)
        build_geomodels(interpolated_variables, codes, tg_grid_name,
                        tg_prop_name, ids, acceptance, rt_prop)

        print('Done!')

        return True
Example #18
0
    def execute(self):

        '''#Execute the funtion read_params
        read_params(self.params)
        print self.params'''

        #Get the grid and rock type propery
        grid = self.params['propertyselectornoregion']['grid']
        prop = self.params['propertyselectornoregion']['property']

        #Error message
        if len(grid) == 0 or len(prop) == 0:
            print 'Select the rocktype property'
            return False

        #Get the X, Y and Z coordinates and RT property
        X = sgems.get_property(grid, '_X_')
        Y = sgems.get_property(grid, '_Y_')
        Z = sgems.get_property(grid, '_Z_')
        RT = sgems.get_property(grid, prop)

        elipsoide = self.params['ellipsoidinput']['value']
        elipsoide_split = elipsoide.split()

        range1 = float(elipsoide_split[0])
        range2 = float(elipsoide_split[1])
        range3 = float(elipsoide_split[2])

        azimuth = float(elipsoide_split[3])
        dip = float(elipsoide_split[4])
        rake = float(elipsoide_split[5])

        X, Y, Z = anis_search(X, Y, Z, range1, range2, range3, azimuth, dip, rake)

        #Creates a list of all rock types
        rt_list = []
        for i in RT:
            if i not in rt_list and not math.isnan(i):
                rt_list.append(i)

        #Sort the rock type list in crescent order
        rt_list = [int(x) for x in rt_list]
        rt_list.sort()

        #Create a empty distance matrix
        dist_matrix = np.zeros(shape = ((len(rt_list)), (len(RT))))

        #Calculates the signed distances, and append it in the distance matrix
        for i in range(len(rt_list)):
            rock = rt_list[i]

            for j in range(len(RT)):

                if math.isnan(RT[j]):
                    dist_matrix[i][j] = float('nan')

                elif RT[j] == rock:
                    dsmin = 1.0e21

                    for k in range(len(RT)):

                        if RT[j] != RT[k] and not math.isnan(RT[k]):
                            if (dist(X[j], Y[j], Z[j], X[k], Y[k], Z[k])) < dsmin:
                                dsmin = (dist(X[j], Y[j], Z[j], X[k], Y[k], Z[k]))

                        dist_matrix[i][j] = -dsmin

                else:
                    dsmin = 1.0e21

                    for k in range(len(RT)):

                        if RT[k] == rock:
                            if (dist(X[j], Y[j], Z[j], X[k], Y[k], Z[k])) < dsmin:
                                dsmin = (dist(X[j], Y[j], Z[j], X[k], Y[k], Z[k]))

                        dist_matrix[i][j] = dsmin

        #Creates the signed distances properties
        lst_props_grid=sgems.get_property_list(grid)

        for k in range(len(dist_matrix)):
            prop_final_data_name = 'Signed_Distances_RT_' + str(rt_list[k])

            if (prop_final_data_name in lst_props_grid):
                flag=0
                i=1
                while (flag==0):
                    test_name=prop_final_data_name+'-'+str(i)
                    if (test_name not in lst_props_grid):
                        flag=1
                        prop_final_data_name=test_name
                    i=i+1

            list = dist_matrix[k].tolist()
            sgems.set_property(grid, prop_final_data_name, list)

        return True
Example #19
0
    def execute(self):
        '''
		VARMAP 
		_____________________________________________________________________________

		This is a template for SGems program variogram and covariance maps.
		The user have to fill the parameters with a ui.file with same name of this python 
		file before start program. The QT userinterface connect SGems data with this routine
		using the class params.
		
		The output of this program is a graphic demonstranting interpolated variogram values 
		along one plane 

	AUTHOR: DAVID ALVARENGA DRUMOND 		2016
	
	'''
        '''
	INITIAL PARAMETERS 
	______________________________________________________________________________

	All initial parameters are transcribe by ui.file interface. Variables are choose 
	among common variables. The follow variables are:

	COMMON VARIABLES: 

	head_property= head property 
	head_grid = head grid 
	tail_property = tail property 
	tail_grid= tail grid 
	C_variogram = check box for variogram maps 
	C_covariance= check box for covariance maps 
	nlags= number of lags in experimental variogram 
	lagdistance = lag length for this experimental variograms 
	lineartolerance= linear tolerance for this map
	htolerance = horizontal tolerance for this map 
	vtolerance = vertical tolerance for this lag
	hband = horizontal band 
	vband = vertical band 
	dip = dip of the rake of variogram map 
	azimute = azimuth of the rake of variogram map
	gdiscrete = number of cells to discretize map 
	ncontour = number of contourn lines to interpolate in map 

	
	'''

        # Stabilish initial parameters

        head_property = self.params['head_prop']['property']
        head_grid = self.params['head_prop']['grid']
        tail_property = self.params['tail_prop']['property']
        tail_grid = self.params['tail_prop']['grid']
        C_variogram = int(self.params['C_variogram']['value'])
        C_covariance = int(self.params['C_covariance']['value'])
        nlags = int(self.params['nlags']['value'])
        lagdistance = float(self.params['lagdistance']['value'])
        lineartolerance = float(self.params['lineartolerance']['value'])
        htolerance = float(self.params['htolangular']['value'])
        vtolerance = float(self.params['vtolangular']['value'])
        hband = float(self.params['hband']['value'])
        vband = float(self.params['vband']['value'])
        dip = float(self.params['Dip']['value'])
        azimute = float(self.params['Azimute']['value'])
        gdiscrete = float(self.params['Gdiscrete']['value'])
        ncontour = int(self.params['ncontour']['value'])

        # Get values from sgems properties

        xh = []
        yh = []
        zh = []
        vh = []

        xh1 = sgems.get_property(head_grid, "_X_")
        yh1 = sgems.get_property(head_grid, "_Y_")
        zh1 = sgems.get_property(head_grid, "_Z_")
        vh1 = sgems.get_property(head_grid, head_property)

        xh, yh, zh, vh = retire_nan(xh1, yh1, zh1, vh1)

        xt = []
        yt = []
        zt = []
        vt = []

        xt1 = sgems.get_property(tail_grid, "_X_")
        yt1 = sgems.get_property(tail_grid, "_Y_")
        zt1 = sgems.get_property(tail_grid, "_Z_")
        vt1 = sgems.get_property(tail_grid, tail_property)

        xt, yt, zt, vt = retire_nan(xt1, yt1, zt1, vt1)

        # Verify dimensions

        # Verify dimensions of head

        cdimensaoxh = False
        cdimensaoyh = False
        cdimensaozh = False

        for x in range(0, len(xh)):
            if (xh[x] != 0):
                cdimensaoxh = True

        for y in range(0, len(yh)):
            if (yh[y] != 0):
                cdimensaoyh = True

        for z in range(0, len(zh)):
            if (zh[z] != 0):
                cdimensaozh = True

        # Verify dimensions of tail

        cdimensaoxt = False
        cdimensaoyt = False
        cdimensaozt = False

        for x in range(0, len(xt)):
            if (xt[x] != 0):
                cdimensaoxt = True

        for y in range(0, len(yt)):
            if (yt[y] != 0):
                cdimensaoyt = True

        for z in range(0, len(zt)):
            if (zt[z] != 0):
                cdimensaozt = True

        if ((cdimensaoxt == cdimensaoxh) and (cdimensaoyt == cdimensaoyh)
                and (cdimensaozt == cdimensaozh)):

            # Define maximum distance permisible

            dmaximo = (nlags + 0.5) * lagdistance

            # Transform tolerances if they are zero

            if (htolerance == 0):
                htolerance = 45
            if (vtolerance == 0):
                vtolerance = 45
            if (hband == 0):
                hband = lagdistance / 2
            if (vband == 0):
                vband = lagdistance / 2
            if (lagdistance == 0):
                lagdistance = 100
            if (lineartolerance == 0):
                lineartolerance = lagdistance / 2

            # Convert tolerances in radians
            htolerance = math.radians(htolerance)
            vtolerance = math.radians(vtolerance)

            # Determine dip and azimuth projections
            htolerance = math.cos(htolerance)
            vtolerance = math.cos(vtolerance)

            # Define all euclidian distances

            cabeca = []
            rabo = []
            cabeca2 = []
            rabo2 = []
            distanciah = []
            distanciaxy = []
            distanciax = []
            distanciay = []
            distanciaz = []
            for t in range(0, len(yt)):
                for h in range(t, len(yh)):
                    cabeca.append(vh[h])
                    rabo.append(vt[t])
                    cabeca2.append(vt[h])
                    rabo2.append(vh[t])
                    dx = xh[h] - xt[t]
                    dy = yh[h] - yt[t]
                    dz = zh[h] - zt[t]
                    if (distanciah > 0):
                        distanciay.append(dy)
                        distanciax.append(dx)
                        distanciaz.append(dz)
                        distanciah.append(
                            math.sqrt(
                                math.pow(dy, 2) + math.pow(dx, 2) +
                                math.pow(dz, 2)))
                        distanciaxy.append(
                            math.sqrt(math.pow(dy, 2) + math.pow(dx, 2)))

            # Calculate all cosine and sine values

            cos_Azimute = []
            sin_Azimute = []
            cos_Dip = []
            sin_Dip = []
            flutuante_d = 0

            for a in range(0, 360, 10):
                diferenca = a + azimute
                cos_Azimute.append(math.cos(math.radians(90 - diferenca)))
                sin_Azimute.append(math.sin(math.radians(90 - diferenca)))
                if (dip != 90 and dip != 180):
                    flutuante_d = math.cos(
                        math.radians(90) - math.fabs(
                            math.atan(
                                math.tan(math.radians(dip)) *
                                math.sin(math.radians(90 - diferenca)))))
                    cos_Dip.append(flutuante_d)
                    flutuante_d = math.sin(
                        math.radians(90) - math.fabs(
                            math.atan(
                                math.tan(math.radians(dip)) *
                                math.sin(math.radians(90 - diferenca)))))
                    sin_Dip.append(flutuante_d)
                else:
                    cos_Dip.append(1)
                    sin_Dip.append(0)

            distancias_admissiveis = []
            azimute_admissiveis = []
            dip_admissiveis = []
            v_valores_admissiveis_h = []
            v_valores_admissiveis_t = []
            v_valores_admissiveis_h2 = []
            v_valores_admissiveis_t2 = []
            pares = []

            # Calculate permissible experimental pairs

            for a in range(0, 36):
                azm = math.radians(a * 10)
                if (dip != 90 and dip != 180):
                    dipatua = math.radians(90) - math.atan(
                        math.tan(math.radians(dip)) *
                        math.sin(math.radians(90 - diferenca)))
                else:
                    dipatua = math.radians(90)
                for l in range(0, nlags):
                    valores_admissiveis_h = []
                    valores_admissiveis_t = []
                    valores_admissiveis_h2 = []
                    valores_admissiveis_t2 = []
                    distancia_admissivel = []
                    azimute_admissivel = []
                    dip_admissivel = []
                    lag = lagdistance * (l + 1)
                    par = 0
                    for p in range(0, len(distanciah)):
                        if (distanciah[p] < dmaximo):
                            limitemin = lag - lineartolerance
                            limitemax = lag + lineartolerance
                            if (distanciah[p] > limitemin
                                    and distanciah[p] < limitemax):
                                if (distanciaxy[p] > 0.000):
                                    check_azimute = (
                                        distanciax[p] * cos_Azimute[a] +
                                        distanciay[p] *
                                        sin_Azimute[a]) / distanciaxy[p]
                                else:
                                    check_azimute = 1
                                check_azimute = math.fabs(check_azimute)
                                if (check_azimute >= htolerance):
                                    check_bandh = (
                                        cos_Azimute[a] * distanciay[p]) - (
                                            sin_Azimute[a] * distanciax[p])
                                    check_bandh = math.fabs(check_bandh)
                                    if (check_bandh < hband):
                                        if (distanciah[p] > 0.000):
                                            check_dip = (
                                                math.fabs(distanciaxy[p]) *
                                                sin_Dip[a] + distanciaz[p] *
                                                cos_Dip[a]) / distanciah[p]
                                        else:
                                            check_dip = 0.000
                                        check_dip = math.fabs(check_dip)
                                        if (check_dip >= vtolerance):
                                            check_bandv = sin_Dip[
                                                a] * distanciaz[p] - cos_Dip[
                                                    a] * math.fabs(
                                                        distanciaxy[p])
                                            check_bandv = math.fabs(
                                                check_bandv)
                                            if (check_bandv < vband):
                                                if (check_dip < 0
                                                        and check_azimute < 0):
                                                    valores_admissiveis_h.append(
                                                        rabo[p])
                                                    valores_admissiveis_t.append(
                                                        cabeca[p])
                                                    valores_admissiveis_h2.append(
                                                        rabo2[p])
                                                    valores_admissiveis_t2.append(
                                                        cabeca2[p])
                                                    distancia_admissivel.append(
                                                        distanciah[p])
                                                    par = par + 1
                                                    azimute_admissivel.append(
                                                        azm)
                                                    dip_admissivel.append(dipv)
                                                else:
                                                    valores_admissiveis_h.append(
                                                        cabeca[p])
                                                    valores_admissiveis_t.append(
                                                        rabo[p])
                                                    valores_admissiveis_h2.append(
                                                        cabeca2[p])
                                                    valores_admissiveis_t2.append(
                                                        rabo2[p])
                                                    distancia_admissivel.append(
                                                        distanciah[p])
                                                    par = par + 1
                                                    azimute_admissivel.append(
                                                        azm)
                                                    dip_admissivel.append(
                                                        dipatua)
                    if (len(valores_admissiveis_h) > 0
                            and len(valores_admissiveis_t) > 0):
                        if (par > 0):
                            v_valores_admissiveis_h.append(
                                valores_admissiveis_h)
                            v_valores_admissiveis_h2.append(
                                valores_admissiveis_h2)
                            v_valores_admissiveis_t2.append(
                                valores_admissiveis_t2)
                            v_valores_admissiveis_t.append(
                                valores_admissiveis_t)
                            distancias_admissiveis.append(distancia_admissivel)
                            pares.append(par)
                            azimute_admissiveis.append(azimute_admissivel)
                            dip_admissiveis.append(dip_admissivel)

            # Calculate continuity functions

            # Variogram

            if (C_variogram == 1):
                continuidade = []
                lag_adm = []
                azimute_adm = []
                dip_adm = []
                for i in range(0, len(v_valores_admissiveis_h)):
                    flutuantet = []
                    flutuanteh = []
                    flutuanteh2 = []
                    flutuantet2 = []
                    flutuanted = []
                    flutuantea = []
                    flutuantedip = []
                    par_var = 0
                    flutuanteh = v_valores_admissiveis_h[i][:]
                    flutuanteh2 = v_valores_admissiveis_h2[i][:]
                    flutuantet = v_valores_admissiveis_t[i][:]
                    flutuantet2 = v_valores_admissiveis_t2[i][:]
                    flutuanted = distancias_admissiveis[i][:]
                    flutuantea = azimute_admissiveis[i][:]
                    flutuantedip = dip_admissiveis[i][:]
                    par_var = pares[i]
                    soma = 0
                    lagmedio = 0
                    agmedio = 0
                    dgmedio = 0
                    for j in range(0, len(flutuanteh)):
                        soma = soma + (flutuanteh[j] - flutuantet2[j]) * (
                            flutuanteh2[j] - flutuantet[j]) / (2 * pares[i])
                    continuidade.append(soma)
                    for z in range(0, len(flutuanted)):
                        lagmedio = lagmedio + flutuanted[z] / len(flutuanted)
                    lag_adm.append(lagmedio)
                    for g in range(0, len(flutuantea)):
                        agmedio = agmedio + flutuantea[g] / len(flutuantea)
                    azimute_adm.append(agmedio)
                    for t in range(0, len(flutuantedip)):
                        dgmedio = dgmedio + flutuantedip[t] / len(flutuantedip)
                    dip_adm.append(dgmedio)

            # Covariogram

            if (C_covariance == 1):
                continuidade = []
                lag_adm = []
                azimute_adm = []
                dip_adm = []
                for i in range(0, len(v_valores_admissiveis_h)):
                    flutuantet = []
                    flutuanteh = []
                    flutuanted = []
                    flutuantea = []
                    flutuantedip = []
                    par_var = 0
                    flutuanteh = v_valores_admissiveis_h[i]
                    flutuantet = v_valores_admissiveis_t[i]
                    flutuanted = distancias_admissiveis[i]
                    flutuantea = azimute_admissiveis[i]
                    flutuantedip = dip_admissiveis[i]
                    par_var = pares[i]
                    soma = 0
                    lagmedio = 0
                    agmedio = 0
                    dgmedio = 0
                    somah = 0
                    somat = 0
                    mediah = 0
                    mediat = 0
                    for d in range(0, len(flutuanteh)):
                        somah = somah + flutuanteh[d]
                    mediah = float(somah / len(flutuanteh))
                    for t in range(0, len(flutuantet)):
                        somat = somat + flutuantet[t]
                    mediat = float(somat / len(flutuantet))
                    for j in range(0, len(flutuanteh)):
                        soma = soma + float(
                            ((flutuanteh[j] - mediah) *
                             (flutuantet[j] - mediat)) / (par_var))
                    continuidade.append(soma)
                    for z in range(0, len(flutuanted)):
                        lagmedio = lagmedio + flutuanted[z] / len(flutuanted)
                    lag_adm.append(lagmedio)
                    for g in range(0, len(flutuantea)):
                        agmedio = agmedio + flutuantea[g] / len(flutuantea)
                    azimute_adm.append(agmedio)
                    for y in range(0, len(flutuantedip)):
                        dgmedio = dgmedio + flutuantedip[y] / len(flutuantedip)
                    dip_adm.append(dgmedio)

            # Plot variograms on map

            x = np.array(lag_adm) * np.sin(np.array(azimute_adm))
            y = np.array(lag_adm) * np.cos(np.array(azimute_adm))

            Xi = np.linspace(-max(x) - lagdistance,
                             max(x) + lagdistance, gdiscrete)
            Yi = np.linspace(-max(y) - lagdistance,
                             max(y) + lagdistance, gdiscrete)

            #make the axes
            f = plt.figure()
            left, bottom, width, height = [0, 0.1, 0.7, 0.7]
            ax = plt.axes([left, bottom, width, height])
            pax = plt.axes([left, bottom, width, height],
                           projection='polar',
                           axisbg='none')

            pax.set_theta_zero_location("N")
            pax.set_theta_direction(-1)

            cax = plt.axes([0.8, 0, 0.05, 1])
            ax.set_aspect(1)
            ax.axis('Off')

            # grid the data.
            Vi = griddata((x, y),
                          np.array(continuidade), (Xi[None, :], Yi[:, None]),
                          method='cubic')
            cf = ax.contourf(Xi, Yi, Vi, ncontour, cmap=plt.cm.jet)

            gradient = np.linspace(-max(continuidade), max(continuidade),
                                   math.fabs(2 * max(continuidade)))
            gradient = np.vstack((gradient, gradient))
            cax.xaxis.set_major_locator(plt.NullLocator())
            cax.yaxis.tick_right()
            cax.imshow(gradient.T, aspect='auto', cmap=plt.cm.jet)

            plt.show()
            plt.close()
Example #20
0
    def execute(self):

	'''
		HSCATTERPLOT 
		_____________________________________________________________________________

		This is a template for SGems program variogram and covariance maps.
		The user have to fill the parameters with a ui.file with same name of this python 
		file before start program. The QT userinterface connect SGems data with this routine
		using the class params.
		
		The output of this program is a graphic demonstranting interpolated variogram values 
		along one plane 

	AUTHOR: DAVID ALVARENGA DRUMOND 		2016
	
	'''	

	'''
	INITIAL PARAMETERS 
	______________________________________________________________________________

	All initial parameters are transcribe by ui.file interface. Variables are choose 
	among common variables. The follow variables are:

	COMMON VARIABLES: 

	head_property= head property 
	head_grid = head grid 
	tail_property = tail property 
	tail_grid= tail grid 
	C_variogram = check box for variogram maps 
	C_covariance= check box for covariance maps 
	nlags= number of lags in experimental variogram 
	lagdistance = lag length for this experimental variograms 
	lineartolerance= linear tolerance for this map
	htolerance = horizontal tolerance for this map 
	vtolerance = vertical tolerance for this lag
	hband = horizontal band 
	vband = vertical band 
	dip = dip of the rake of variogram map 
	azimute = azimuth of the rake of variogram map
	gdiscrete = number of cells to discretize map 
	ncontour = number of contourn lines to interpolate in map 

	
	'''


	# Stabilish initial parameters 

	head_property= self.params['head_prop']['property']
	head_grid = self.params['head_prop']['grid']
	tail_property = self.params['tail_prop']['property']
	tail_grid= self.params['tail_prop']['grid']
	nlags= int(self.params['nlags']['value'])
	lagdistance = float(self.params['lagdistance']['value'])
	lineartolerance= float(self.params['lineartolerance']['value'])
	htolerance = float(self.params['htolangular']['value'])
	vtolerance = float(self.params['vtolangular']['value'])
	hband = float(self.params['hband']['value'])
	vband = float(self.params['vband']['value'])
	Dip = float(self.params['Dip']['value'])
	Azimute= float(self.params['Azimute']['value'])

	print (self.params)
	
	# Get values from SGems and exclude nan values  
	
	xh = []
	yh = []
	zh = [] 
	vh = []
	
	xh1 = sgems.get_property(head_grid, "_X_")
	yh1 = sgems.get_property(head_grid, "_Y_")
	zh1 = sgems.get_property(head_grid, "_Z_")
	vh1 = sgems.get_property(head_grid, head_property)	

	xh, yh, zh, vh = retire_nan(xh1,yh1,zh1,vh1)


	xt = []
	yt = []
	zt = []	
	vt = []

	xt1 = sgems.get_property(tail_grid, "_X_")
	yt1 = sgems.get_property(tail_grid, "_Y_")
	zt1 = sgems.get_property(tail_grid, "_Z_")
	vt1 = sgems.get_property(tail_grid, tail_property)

	xt, yt, zt, vt = retire_nan(xt1,yt1,zt1,vt1)	

	# Verify number of dimensions of problem
	
	# Verify dimensions of head 

	cdimensaoxh = False
	cdimensaoyh = False
	cdimensaozh = False

	for x in range(0,len(xh)):
		if (xh[x] != 0):
			cdimensaoxh = True


	for y in range(0,len(yh)):
		if (yh[y] != 0):
			cdimensaoyh = True


	for z in range(0,len(zh)):
		if (zh[z] != 0):
			cdimensaozh = True

	# Verify dimensions of tail 

	cdimensaoxt = False
	cdimensaoyt = False
	cdimensaozt = False

	for x in range(0,len(xt)):
		if (xt[x] != 0):
			cdimensaoxt = True

	for y in range(0,len(yt)):
		if (yt[y] != 0):
			cdimensaoyt = True


	for z in range(0,len(zt)):
		if (zt[z] != 0):
			cdimensaozt = True

	if ((cdimensaoxt == cdimensaoxh) and (cdimensaoyt == cdimensaoyh) and (cdimensaozt == cdimensaozh)):
		


		# Define maximum distance permissible 
		
		dmaximo = (nlags + 0.5)*lagdistance
		
		# Define tolerances if they are zero 
 
		if (htolerance == 0):
			htolerance= 45
		if (vtolerance == 0):
			vtolerance = 45
		if (hband == 0):
			hband = lagdistance/2
		if (vband == 0):
			vband = lagdistance/2
		if (lagdistance == 0):		
			lagdistance = 100
		if (lineartolerance == 0):
			lineartolerance = lagdistance/2
		
		
		
	
		# Convert tolerances in radians 

		htolerance = math.radians(htolerance)
		vtolerance = math.radians(vtolerance)	

		# Determine dip and azimuth projections  
		htolerance = math.cos(htolerance)
		vtolerance = math.cos(vtolerance)
	
		# Define all euclidian distances permissible 
		
		cabeca = []
		rabo = []
		distanciah =[]	
		distanciaxy =[]	
		distanciax =[]
		distanciay = []
 		distanciaz = []
		for t in range(0, len(yt)):
			for h in range(t, len(yh)):
				cabeca.append(vh[h])
				rabo.append(vt[t])
				dx = xh[h]-xt[t] 				
				dy= yh[h]-yt[t]
				dz = zh[h]-zt[t]
				if (distanciah > 0):
					distanciay.append(dy)
					distanciax.append(dx)
					distanciaz.append(dz)
					distanciah.append(math.sqrt(math.pow(dy,2) + math.pow(dx,2) + math.pow(dz,2)))						
					distanciaxy.append(math.sqrt(math.pow(dy,2) + math.pow(dx,2)))

		# Calculate all cos and sin values 		
	
		cos_Azimute = math.cos(math.radians(90-Azimute))
		sin_Azimute = math.sin(math.radians(90-Azimute))
		sin_Dip = math.sin(math.radians(90-Dip))
		cos_Dip = math.cos(math.radians(90-Dip))
	
		v_valores_admissiveis_h =[]
		v_valores_admissiveis_t =[]
		

		# Calculate admissible points  
		
		

		for l in range(0, nlags):			
			valores_admissiveis_h = []
			valores_admissiveis_t = []
			lag= lagdistance*(l+1)
			for p in range(0,len(distanciah)):
				if (distanciah[p] < dmaximo):
					limitemin = lag - lineartolerance
					limitemax = lag + lineartolerance
					if (distanciah[p] > limitemin and distanciah[p] < limitemax):					
						if (distanciaxy[p] > 0.000): 				
							check_azimute = (distanciax[p]*cos_Azimute +distanciay[p]*sin_Azimute)/distanciaxy[p]
						else:
							check_azimute = 1
						check_azimute = math.fabs(check_azimute)
						if (check_azimute >= htolerance):							
							check_bandh = (cos_Azimute*distanciay[p]) - (sin_Azimute*distanciax[p])
							check_bandh = math.fabs(check_bandh)
							if (check_bandh < hband):							
								if(distanciah[p] > 0.000):
									check_dip = (math.fabs(distanciaxy[p])*sin_Dip + distanciaz[p]*cos_Dip)/distanciah[p]
								else:
									check_dip = 0.000
								check_dip = math.fabs(check_dip) 
								if (check_dip >= vtolerance):
									check_bandv = sin_Dip*distanciaz[p] - cos_Dip*math.fabs(distanciaxy[p])
									check_bandv = math.fabs(check_bandv)
									if (check_bandv < vband):
										if (check_dip <0 and check_azimute <0):
											valores_admissiveis_h.append(rabo[p])
											valores_admissiveis_t.append(cabeca[p])
										else:
											valores_admissiveis_h.append(cabeca[p])
											valores_admissiveis_t.append(rabo[p])	
			if (len(valores_admissiveis_h) > 0 and len(valores_admissiveis_t) > 0):				
				v_valores_admissiveis_h.append(valores_admissiveis_h)
				v_valores_admissiveis_t.append(valores_admissiveis_t)
		

		for i in range(0,len(v_valores_admissiveis_h)):
			vh = []
			vt = []
			vh = np.array(v_valores_admissiveis_h[i])
			vt = np.array(v_valores_admissiveis_t[i])
			

			slope, intercept, r_value, p_value, std_err = stats.linregress(vh,vt)
			plt.title("Hscatter plot for lag: " + str(lagdistance*(i+1)) + " correlation: " + str(r_value))			
			plt.plot(vh,vt,'ro',vh,slope*vh+intercept,'b-')
			plt.show()
	

		
	
					
    	return True 
Example #21
0
    def execute(self):
        print(self.params)
        '''
		EXPERIMENTAL VARIOGRAMS CALCULATION 
		_____________________________________________________________________________

		This is a template for SGems program for calculating experimental variograms.
		The user have to fill the parameters with a ui.file with same name of this python 
		file before start program. The QT userinterface connect SGems data with this routine
		using the class params.
		
		The output of this program is two files, one relatory with all experimental points 
		used in Automatic fitting procedure and other with a hml file used to import 
		experimental variograms in SGems

	AUTHOR: DAVID ALVARENGA DRUMOND 		2016
	
	'''
        '''
	INITIAL PARAMETERS 
	______________________________________________________________________________

	All initial parameters are transcribe by ui.file interface. Variables are choose 
	among common variables. The follow variables are:

	COMMON VARIABLES: 

	head_property= adress of head property
	head_grid = adress of head grid 
	tail_property = adress of tail property
	tail_grid= adress of tail grid 
	C_variogram = check for variogram function calculation 
	C_covariance= check for covariance function calculation 
	C_relative_variogram = check for relative variogram calculation
	C_madogram = check for madogram calculation 
	C_correlogram = check for correlogram calculation 
	C_PairWise = check for pairwise calcluation 
	nlags= number of lags in experimental variogram 
	lagdistance = lenght of lag in experimental variogram 
	lineartolerance= linear tolerance of experimental variogram 
	htolerance = horizontal angular tolerance
	vtolerance = vertical angular tolerance
	hband = horizontal bandwidth
	vband = vertical bandwidth
	nAzimuths = number of azimuths 
	NDips = number of dips 
	Azimth_diference = angular diference between azimuths 
	Dip_difference = angular diference between dips
	sAzimuth = initial azimuth value
	sDip = initial dip value 
	inv = choose of invert correlogram axis 
	save = save adress of relatory file 
	save2 = save adress of Sgems variogram file 
	nhead = number of head to print in relatory file 
	ntail = number of tail to print in relatory file 

	
	'''

        # Stabilish initial parameters

        head_property = self.params['head_prop']['property']
        head_grid = self.params['head_prop']['grid']
        tail_property = self.params['tail_prop']['property']
        tail_grid = self.params['tail_prop']['grid']
        C_variogram = int(self.params['C_variogram']['value'])
        C_covariance = int(self.params['C_covariance']['value'])
        C_relative_variogram = int(
            self.params['C_relative_variogram']['value'])
        C_madogram = int(self.params['C_madogram']['value'])
        C_correlogram = int(self.params['C_correlogram']['value'])
        C_PairWise = int(self.params['C_PairWise']['value'])
        nlags = int(self.params['nlags']['value'])
        lagdistance = float(self.params['lagdistance']['value'])
        lineartolerance = float(self.params['lineartolerance']['value'])
        htolerance = float(self.params['htolangular']['value'])
        vtolerance = float(self.params['vtolangular']['value'])
        hband = float(self.params['hband']['value'])
        vband = float(self.params['vband']['value'])
        nAzimuths = int(self.params['nAzimuths']['value'])
        NDips = int(self.params['NDips']['value'])
        Azimth_diference = float(self.params['Azimth_diference']['value'])
        Dip_difference = float(self.params['Dip_difference']['value'])
        sAzimuth = float(self.params['sAzimuth']['value'])
        sDip = float(self.params['sDip']['value'])
        inv = int(self.params['Inv']['value'])
        save = self.params['Save']['value']
        save2 = self.params['Save2']['value']
        nhead = self.params['NHEAD']['value']
        ntail = self.params['NTAIL']['value']

        # Obtain properties in SGems

        xh = []
        yh = []
        zh = []
        vh = []

        xh1 = sgems.get_property(head_grid, "_X_")
        yh1 = sgems.get_property(head_grid, "_Y_")
        zh1 = sgems.get_property(head_grid, "_Z_")
        vh1 = sgems.get_property(head_grid, head_property)

        xh, yh, zh, vh = retire_nan(xh1, yh1, zh1, vh1)

        xt = []
        yt = []
        zt = []
        vt = []

        xt1 = sgems.get_property(tail_grid, "_X_")
        yt1 = sgems.get_property(tail_grid, "_Y_")
        zt1 = sgems.get_property(tail_grid, "_Z_")
        vt1 = sgems.get_property(tail_grid, tail_property)

        xt, yt, zt, vt = retire_nan(xt1, yt1, zt1, vt1)

        # Verify number of dimensions in the problem

        # Verify number of dimensions in head

        cdimensaoxh = False
        cdimensaoyh = False
        cdimensaozh = False

        for x in range(0, len(xh)):
            if (xh[x] != 0):
                cdimensaoxh = True

        for y in range(0, len(yh)):
            if (yh[y] != 0):
                cdimensaoyh = True

        for z in range(0, len(zh)):
            if (zh[z] != 0):
                cdimensaozh = True

        # Verify number of dimensions in tail

        cdimensaoxt = False
        cdimensaoyt = False
        cdimensaozt = False

        for x in range(0, len(xt)):
            if (xt[x] != 0):
                cdimensaoxt = True

        for y in range(0, len(yt)):
            if (yt[y] != 0):
                cdimensaoyt = True

        for z in range(0, len(zt)):
            if (zt[z] != 0):
                cdimensaozt = True

        if ((cdimensaoxt == cdimensaoxh) and (cdimensaoyt == cdimensaoyh)
                and (cdimensaozt == cdimensaozh)):

            # Define maximum permissible distance

            dmaximo = (nlags + 0.5) * lagdistance

            #Transform tolerances if they are zero

            if (htolerance == 0):
                htolerance = 45
            if (vtolerance == 0):
                vtolerance = 45
            if (hband == 0):
                hband = lagdistance / 2
            if (vband == 0):
                vband = lagdistance / 2
            if (lagdistance == 0):
                lagdistance = 100
            if (lineartolerance == 0):
                lineartolerance = lagdistance / 2

            #Convert tolerances in radians
            htolerance = math.radians(htolerance)
            vtolerance = math.radians(vtolerance)

            # Determine projections of Dip and Azimuth
            htolerance = math.cos(htolerance)
            vtolerance = math.cos(vtolerance)

            # Define all direction distances

            cabeca = []
            rabo = []
            cabeca2 = []
            rabo2 = []
            distanciah = []
            distanciaxy = []
            distanciax = []
            distanciay = []
            distanciaz = []
            for t in range(0, len(yt)):
                for h in range(t, len(yh)):
                    cabeca.append(vh[h])
                    rabo.append(vt[t])
                    cabeca2.append(vt[h])
                    rabo2.append(vh[t])
                    dx = xh[h] - xt[t]
                    dy = yh[h] - yt[t]
                    dz = zh[h] - zt[t]
                    if (distanciah > 0):
                        distanciay.append(dy)
                        distanciax.append(dx)
                        distanciaz.append(dz)
                        distanciah.append(
                            math.sqrt(
                                math.pow(dy, 2) + math.pow(dx, 2) +
                                math.pow(dz, 2)))
                        distanciaxy.append(
                            math.sqrt(math.pow(dy, 2) + math.pow(dx, 2)))

            # Calculate all sin and cosine functions of Dip and Azimuth

            azimute = []
            fAzimuth = float(Azimth_diference * (nAzimuths - 1)) + sAzimuth
            azimute = np.linspace(sAzimuth, fAzimuth, nAzimuths)

            dip = []
            fDip = Dip_difference * (NDips - 1) + sDip
            dip = np.linspace(sDip, fDip, NDips)

            cos_Azimute = []
            sin_Azimute = []
            for a in azimute:
                cos_Azimute.append(math.cos(math.radians(90 - a)))
                sin_Azimute.append(math.sin(math.radians(90 - a)))
            cos_Dip = []
            sin_Dip = []
            for a in dip:
                cos_Dip.append(math.cos(math.radians(90 - a)))
                sin_Dip.append(math.sin(math.radians(90 - a)))

            distancias_admissiveis = []
            azimute_admissiveis = []
            dip_admissiveis = []
            v_valores_admissiveis_h = []
            v_valores_admissiveis_t = []
            v_valores_admissiveis_h2 = []
            v_valores_admissiveis_t2 = []
            pares = []

            # Calculate admissible pairs
            for a in range(0, len(azimute)):
                azm = azimute[a]
                for d in range(0, len(dip)):
                    dipv = dip[d]
                    for l in range(0, nlags):
                        valores_admissiveis_h = []
                        valores_admissiveis_t = []
                        valores_admissiveis_h2 = []
                        valores_admissiveis_t2 = []
                        distancia_admissivel = []
                        azimute_admissivel = []
                        dip_admissivel = []
                        lag = lagdistance * (l + 1)
                        par = 0
                        for p in range(0, len(distanciah)):
                            if (distanciah[p] < dmaximo):
                                limitemin = lag - lineartolerance
                                limitemax = lag + lineartolerance
                                if (distanciah[p] > limitemin
                                        and distanciah[p] < limitemax):
                                    if (distanciaxy[p] > 0.000):
                                        check_azimute = (
                                            distanciax[p] * cos_Azimute[a] +
                                            distanciay[p] *
                                            sin_Azimute[a]) / distanciaxy[p]
                                    else:
                                        check_azimute = 1
                                    check_azimute = math.fabs(check_azimute)
                                    if (check_azimute >= htolerance):
                                        check_bandh = (
                                            cos_Azimute[a] * distanciay[p]) - (
                                                sin_Azimute[a] * distanciax[p])
                                        check_bandh = math.fabs(check_bandh)
                                        if (check_bandh < hband):
                                            if (distanciah[p] > 0.000):
                                                check_dip = (
                                                    math.fabs(distanciaxy[p]) *
                                                    sin_Dip[d] +
                                                    distanciaz[p] *
                                                    cos_Dip[d]) / distanciah[p]
                                            else:
                                                check_dip = 0.000
                                            check_dip = math.fabs(check_dip)
                                            if (check_dip >= vtolerance):
                                                check_bandv = sin_Dip[
                                                    d] * distanciaz[
                                                        p] - cos_Dip[
                                                            d] * math.fabs(
                                                                distanciaxy[p])
                                                check_bandv = math.fabs(
                                                    check_bandv)
                                                if (check_bandv < vband):
                                                    if (check_dip < 0 and
                                                            check_azimute < 0):
                                                        valores_admissiveis_h.append(
                                                            rabo[p])
                                                        valores_admissiveis_t.append(
                                                            cabeca[p])
                                                        valores_admissiveis_h2.append(
                                                            rabo2[p])
                                                        valores_admissiveis_t2.append(
                                                            cabeca2[p])
                                                        distancia_admissivel.append(
                                                            distanciah[p])
                                                        par = par + 1
                                                        azimute_admissivel.append(
                                                            azm)
                                                        dip_admissivel.append(
                                                            dipv)
                                                    else:
                                                        valores_admissiveis_h.append(
                                                            cabeca[p])
                                                        valores_admissiveis_t.append(
                                                            rabo[p])
                                                        valores_admissiveis_h2.append(
                                                            cabeca2[p])
                                                        valores_admissiveis_t2.append(
                                                            rabo2[p])
                                                        distancia_admissivel.append(
                                                            distanciah[p])
                                                        par = par + 1
                                                        azimute_admissivel.append(
                                                            azm)
                                                        dip_admissivel.append(
                                                            dipv)
                        if (len(valores_admissiveis_h) > 0
                                and len(valores_admissiveis_t) > 0):
                            v_valores_admissiveis_h.append(
                                valores_admissiveis_h)
                            v_valores_admissiveis_h2.append(
                                valores_admissiveis_h2)
                            v_valores_admissiveis_t2.append(
                                valores_admissiveis_t2)
                            v_valores_admissiveis_t.append(
                                valores_admissiveis_t)
                            distancias_admissiveis.append(distancia_admissivel)
                            pares.append(par)
                            azimute_admissiveis.append(azimute_admissivel)
                            dip_admissiveis.append(dip_admissivel)

            # Calculate continuity functions

            # Variogram

            if (C_variogram == 1):
                continuidade = []
                lag_adm = []
                azimute_adm = []
                dip_adm = []
                for i in range(0, len(v_valores_admissiveis_h)):
                    flutuantet = []
                    flutuanteh = []
                    flutuanteh2 = []
                    flutuantet2 = []
                    flutuanted = []
                    flutuantea = []
                    flutuantedip = []
                    par_var = 0
                    flutuanteh = v_valores_admissiveis_h[i][:]
                    flutuanteh2 = v_valores_admissiveis_h2[i][:]
                    flutuantet = v_valores_admissiveis_t[i][:]
                    flutuantet2 = v_valores_admissiveis_t2[i][:]
                    flutuanted = distancias_admissiveis[i][:]
                    flutuantea = azimute_admissiveis[i][:]
                    flutuantedip = dip_admissiveis[i][:]
                    par_var = pares[i]
                    soma = 0
                    lagmedio = 0
                    agmedio = 0
                    dgmedio = 0
                    for j in range(0, len(flutuanteh)):
                        soma = soma + (flutuanteh[j] - flutuantet2[j]) * (
                            flutuanteh2[j] - flutuantet[j]) / (2 * pares[i])
                    continuidade.append(soma)
                    for z in range(0, len(flutuanted)):
                        lagmedio = lagmedio + flutuanted[z] / len(flutuanted)
                    lag_adm.append(lagmedio)
                    for g in range(0, len(flutuantea)):
                        agmedio = agmedio + flutuantea[g] / len(flutuantea)
                    azimute_adm.append(agmedio)
                    for t in range(0, len(flutuantedip)):
                        dgmedio = dgmedio + flutuantedip[t] / len(flutuantedip)
                    dip_adm.append(dgmedio)

            # Covariogram
            if (C_covariance == 1):
                continuidade = []
                lag_adm = []
                azimute_adm = []
                dip_adm = []
                for i in range(0, len(v_valores_admissiveis_h)):
                    flutuantet = []
                    flutuanteh = []
                    flutuanted = []
                    flutuantea = []
                    flutuantedip = []
                    par_var = 0
                    flutuanteh = v_valores_admissiveis_h[i]
                    flutuantet = v_valores_admissiveis_t[i]
                    flutuanted = distancias_admissiveis[i]
                    flutuantea = azimute_admissiveis[i]
                    flutuantedip = dip_admissiveis[i]
                    par_var = pares[i]
                    soma = 0
                    lagmedio = 0
                    agmedio = 0
                    dgmedio = 0
                    somah = 0
                    somat = 0
                    mediah = 0
                    mediat = 0
                    for d in range(0, len(flutuanteh)):
                        somah = somah + flutuanteh[d]
                    mediah = float(somah / len(flutuanteh))
                    for t in range(0, len(flutuantet)):
                        somat = somat + flutuantet[t]
                    mediat = float(somat / len(flutuantet))
                    for j in range(0, len(flutuanteh)):
                        soma = soma + float(
                            ((flutuanteh[j] - mediah) *
                             (flutuantet[j] - mediat)) / (par_var))
                    continuidade.append(soma)
                    for z in range(0, len(flutuanted)):
                        lagmedio = lagmedio + flutuanted[z] / len(flutuanted)
                    lag_adm.append(lagmedio)
                    for g in range(0, len(flutuantea)):
                        agmedio = agmedio + flutuantea[g] / len(flutuantea)
                    azimute_adm.append(agmedio)
                    for y in range(0, len(flutuantedip)):
                        dgmedio = dgmedio + flutuantedip[y] / len(flutuantedip)
                    dip_adm.append(dgmedio)

            # Correlogram
            if (C_correlogram == 1):
                continuidade = []
                lag_adm = []
                azimute_adm = []
                dip_adm = []
                for i in range(0, len(v_valores_admissiveis_h)):
                    flutuantet = []
                    flutuanteh = []
                    flutuanted = []
                    flutuantea = []
                    flutuantedip = []
                    par_var = 0
                    flutuanteh = v_valores_admissiveis_h[i]
                    flutuantet = v_valores_admissiveis_t[i]
                    flutuanted = distancias_admissiveis[i]
                    flutuantea = azimute_admissiveis[i]
                    flutuantedip = dip_admissiveis[i]
                    par_var = pares[i]
                    soma = 0
                    lagmedio = 0
                    agmedio = 0
                    dgmedio = 0
                    somah = 0
                    somat = 0
                    diferencah = 0
                    diferencat = 0
                    mediah = 0
                    mediat = 0
                    varh = 0
                    vart = 0
                    for d in range(0, len(flutuanteh)):
                        somah = somah + flutuanteh[d]
                    mediah = float(somah / len(flutuanteh))
                    for t in range(0, len(flutuantet)):
                        somat = somat + flutuantet[t]
                    mediat = float(somat / len(flutuantet))
                    for u in range(0, len(flutuanteh)):
                        diferencah = flutuanteh[u]**2 + diferencah
                    varh = math.sqrt(
                        float(diferencah) / len(flutuanteh) - mediah**2)
                    for m in range(0, len(flutuanteh)):
                        diferencat = flutuantet[m]**2 + diferencat
                    vart = math.sqrt(
                        float(diferencat) / len(flutuantet) - mediat**2)
                    for j in range(0, len(flutuanteh)):
                        if (vart > 0 and varh > 0):
                            if (inv == 1):
                                soma = soma + 1 - (flutuanteh[j] - mediah) * (
                                    flutuantet[j] - mediat) / (par_var * vart *
                                                               varh)
                            else:
                                soma = soma + (flutuanteh[j] - mediah) * (
                                    flutuantet[j] - mediat) / (par_var * vart *
                                                               varh)
                    continuidade.append(soma)
                    for z in range(0, len(flutuanted)):
                        lagmedio = lagmedio + flutuanted[z] / len(flutuanted)
                    lag_adm.append(lagmedio)
                    for g in range(0, len(flutuantea)):
                        agmedio = agmedio + flutuantea[g] / len(flutuantea)
                    azimute_adm.append(agmedio)
                    for y in range(0, len(flutuantedip)):
                        dgmedio = dgmedio + flutuantedip[y] / len(flutuantedip)
                    dip_adm.append(dgmedio)

            # PairWise
            if (C_PairWise == 1):
                continuidade = []
                lag_adm = []
                azimute_adm = []
                dip_adm = []
                for i in range(0, len(v_valores_admissiveis_h)):
                    flutuantet = []
                    flutuanteh = []
                    flutuanted = []
                    flutuantea = []
                    flutuantedip = []
                    par_var = 0
                    flutuanteh = v_valores_admissiveis_h[i][:]
                    flutuantet = v_valores_admissiveis_t[i][:]
                    flutuanted = distancias_admissiveis[i][:]
                    flutuantea = azimute_admissiveis[i][:]
                    flutuantedip = dip_admissiveis[i][:]
                    par_var = pares[i]
                    soma = 0
                    lagmedio = 0
                    agmedio = 0
                    dgmedio = 0
                    for j in range(0, len(flutuanteh)):
                        s = ((flutuanteh[j] - flutuantet[j]) /
                             (flutuanteh[j] + flutuantet[j]))**2
                        soma = soma + 2 * s / (1.0 * par_var)
                    continuidade.append(soma)
                    for z in range(0, len(flutuanted)):
                        lagmedio = lagmedio + flutuanted[z] / len(flutuanted)
                    lag_adm.append(lagmedio)
                    for g in range(0, len(flutuantea)):
                        agmedio = agmedio + flutuantea[g] / len(flutuantea)
                    azimute_adm.append(agmedio)
                    for t in range(0, len(flutuantedip)):
                        dgmedio = dgmedio + flutuantedip[t] / len(flutuantedip)
                    dip_adm.append(dgmedio)

            # Relative Variogram
            if (C_relative_variogram == 1):
                continuidade = []
                lag_adm = []
                azimute_adm = []
                dip_adm = []
                for i in range(0, len(v_valores_admissiveis_h)):
                    flutuantet = []
                    flutuanteh = []
                    flutuanteh2 = []
                    flutuantet2 = []
                    flutuanted = []
                    flutuantea = []
                    flutuantedip = []
                    par_var = 0
                    flutuanteh = v_valores_admissiveis_h[i]
                    flutuantet = v_valores_admissiveis_t[i]
                    flutuanteh2 = v_valores_admissiveis_h2[i]
                    flutuantet2 = v_valores_admissiveis_t2[i]
                    flutuanted = distancias_admissiveis[i]
                    flutuantea = azimute_admissiveis[i]
                    flutuantedip = dip_admissiveis[i]
                    par_var = pares[i]
                    soma = 0
                    lagmedio = 0
                    agmedio = 0
                    dgmedio = 0
                    somah = 0
                    somat = 0
                    mediah = 0
                    mediat = 0
                    for d in range(0, len(flutuanteh)):
                        somah = somah + flutuanteh[d]
                    mediah = float(somah / len(flutuanteh))
                    for t in range(0, len(flutuantet)):
                        somat = somat + flutuantet[t]
                    mediat = float(somat / len(flutuantet))
                    for j in range(0, len(flutuanteh)):
                        soma = soma + float(
                            (flutuanteh[j] - flutuantet2[j]) *
                            (flutuanteh2[j] - flutuantet2[j]) /
                            (par_var * (mediat + mediah)**2 / 4))
                    continuidade.append(soma)
                    for z in range(0, len(flutuanted)):
                        lagmedio = lagmedio + flutuanted[z] / len(flutuanted)
                    lag_adm.append(lagmedio)
                    for g in range(0, len(flutuantea)):
                        agmedio = agmedio + flutuantea[g] / len(flutuantea)
                    azimute_adm.append(agmedio)
                    for y in range(0, len(flutuantedip)):
                        dgmedio = dgmedio + flutuantedip[y] / len(flutuantedip)
                    dip_adm.append(dgmedio)

            # Madogram
            if (C_madogram == 1):
                continuidade = []
                lag_adm = []
                azimute_adm = []
                dip_adm = []
                for i in range(0, len(v_valores_admissiveis_h)):
                    flutuantet = []
                    flutuanteh = []
                    flutuanted = []
                    flutuantea = []
                    flutuantedip = []
                    par_var = 0
                    flutuanteh = v_valores_admissiveis_h[i]
                    flutuantet = v_valores_admissiveis_t[i]
                    flutuanted = distancias_admissiveis[i]
                    flutuantea = azimute_admissiveis[i]
                    flutuantedip = dip_admissiveis[i]
                    par_var = pares[i]
                    soma = 0
                    lagmedio = 0
                    agmedio = 0
                    dgmedio = 0
                    for j in range(0, len(flutuanteh)):
                        soma = soma + float(
                            math.fabs(flutuanteh[j] - flutuantet[j]) /
                            (2 * par_var))
                    continuidade.append(soma)
                    for z in range(0, len(flutuanted)):
                        lagmedio = lagmedio + flutuanted[z] / len(flutuanted)
                    lag_adm.append(lagmedio)
                    for g in range(0, len(flutuantea)):
                        agmedio = agmedio + flutuantea[g] / len(flutuantea)
                    azimute_adm.append(agmedio)
                    for t in range(0, len(flutuantedip)):
                        dgmedio = dgmedio + flutuantedip[t] / len(flutuantedip)
                    dip_adm.append(dgmedio)

            # Write experimental variograms in relatory

            save = open(save, "a")
            save.write(nhead + "\n")
            save.write(ntail + "\n")
            save.write(" Azimuth	Dip	lag	variogram	pairs \n")
            for i in range(0, len(continuidade)):
                save.write(
                    str(azimute_adm[i]) + "	" + str(dip_adm[i]) + "	" +
                    str(lag_adm[i]) + "	" + str(continuidade[i]) + "	" +
                    str(pares[i]) + "\n")

            # Separate experimental variograms according prescribe direction

            posicao = []
            posicao.append(-1)
            for i in range(1, len(azimute_adm)):
                if (round(azimute_adm[i], 2) != round(azimute_adm[i - 1], 2)
                        or round(dip_adm[i], 2) != round(dip_adm[i - 1], 2)):
                    posicao.append(i - 1)
            posicao.append(len(azimute_adm) - 1)

            azimutes = []
            dips = []
            lags = []
            continuidades = []
            paresv = []

            for i in range(1, len(posicao)):
                azimutes.append(azimute_adm[posicao[i - 1] + 1:posicao[i]])
                dips.append(dip_adm[posicao[i - 1] + 1:posicao[i]])
                lags.append(lag_adm[posicao[i - 1] + 1:posicao[i]])
                continuidades.append(continuidade[posicao[i - 1] +
                                                  1:posicao[i]])
                paresv.append(pares[posicao[i - 1] + 1:posicao[i]])

            # Write hml file for experimental variograms

            save2 = open(save2, "w")
            save2.write("    <experimental_variograms> \n")

            for i in range(0, len(azimutes)):
                azim = []
                Dip = []
                lagv = []
                cont = []
                par = []
                azim = azimutes[i]
                Dip = dips[i]
                lagv = lags[i]
                cont = continuidades[i]
                par = paresv[i]
                save2.write("  <variogram> \n")
                save2.write("  <title>variogram -azth=" +
                            str(round(azim[0], 2)) + ", dip=" +
                            str(round(Dip[0], 2)) + "</title> \n")
                direction1 = math.sin(Dip[0]) * math.cos(azim[0])
                direction2 = math.sin(Dip[0]) * math.sin(azim[0])
                direction3 = -math.sin(Dip[0])
                save2.write("<direction>" + str(direction1) + " " +
                            str(direction2) + " " + str(direction3) +
                            "</direction> \n")
                save2.write("   <x>")
                for j in range(0, len(lagv)):
                    save2.write(str(lagv[j]) + " ")
                save2.write("</x> \n")
                save2.write("   <y>")
                for p in range(0, len(cont)):
                    save2.write(str(cont[p]) + " ")
                save2.write("</y> \n")
                save2.write("   <pairs>")
                for h in range(0, len(cont)):
                    save2.write(str(par[h]) + " ")
                save2.write("</pairs> \n")
                save2.write("  </variogram> \n")
            save2.write("   </experimental_variograms> \n")
            save2.close()

        print("Finish")

        return True
Example #22
0
    def execute(self):

        #aqui vai o codigo
        #getting variables
        tg_grid_name = self.params['gridselector']['value']
        tg_region_name = self.params['gridselector']['region']
        tg_prop_name = self.params['lineEdit']['value']
        prop_grid_name = self.params['propertyselectornoregion']['grid']
        prop_name = self.params['propertyselectornoregion']['property']

        cmin = str_to_float(self.params['lineEdit_3']['value'])
        cmax = str_to_float(self.params['lineEdit_2']['value'])
        gamma_min = str_to_float(self.params['lineEdit_5']['value'])
        gamma_max = str_to_float(self.params['lineEdit_4']['value'])
        n = int(self.params['spinBox']['value'])

        n_folds = int(self.params['spinBox_2']['value'])

        values = np.array(sgems.get_property(prop_grid_name, prop_name))
        nan_filter = np.isfinite(values)
        y_val = values[nan_filter]

        x, y, z = np.array(sgems.get_X(prop_grid_name))[nan_filter], np.array(
            sgems.get_Y(prop_grid_name))[nan_filter], np.array(
                sgems.get_Z(prop_grid_name))[nan_filter]
        X = np.array([x, y, z]).T

        grid = helpers.ar2gemsgrid_to_ar2gasgrid(tg_grid_name, tg_region_name)
        X_new = grid.locations()

        #scaling
        scaler = MinMaxScaler(feature_range=(0, 1))
        X = scaler.fit_transform(X)
        X_new = scaler.fit_transform(X_new)

        #grid search parameters
        C = np.linspace(cmin, cmax, n)
        gamma = np.linspace(gamma_min, gamma_max, n)
        param_grid = [
            {
                'estimator__C': C,
                'estimator__gamma': gamma,
                'estimator__kernel': ["rbf"] * n
            },
        ]

        #clf
        print("Tunning parameters...")
        clf = OneVsOneClassifier(SVC())
        model_tunning = GridSearchCV(clf, param_grid=param_grid, cv=n_folds)
        model_tunning.fit(X, y_val)

        print('accuracy ', model_tunning.best_score_)
        print('parameters', model_tunning.best_params_)

        clf = model_tunning.best_estimator_

        print("Predicting...")
        clf.fit(X, y_val)
        results = clf.predict(X_new)

        tp = np.ones(grid.size_of_mask()) * float('nan') if hasattr(
            grid, 'mask') else np.ones(grid.size()) * float('nan')
        if hasattr(grid, 'mask'):
            mask = grid.mask()
            r_idx = 0
            for idx, val in enumerate(mask):
                if val == True:
                    tp[idx] = results[r_idx]
                    r_idx = r_idx + 1
        else:
            tp = results

        sgems.set_property(tg_grid_name, tg_prop_name, tp.tolist())
        print('Done!')

        return True
Example #23
0
    def execute(self):
        '''#Execute the funtion read_params
        read_params(self.params)
        print self.params'''

        #Get the grid and rock type propery
        grid = self.params['propertyselectornoregion']['grid']
        prop = self.params['propertyselectornoregion']['property']

        #Error message
        if len(grid) == 0 or len(prop) == 0:
            print 'Select the rocktype property'
            return False

        #Get the X, Y and Z coordinates and RT property
        X = sgems.get_property(grid, '_X_')
        Y = sgems.get_property(grid, '_Y_')
        Z = sgems.get_property(grid, '_Z_')
        RT = sgems.get_property(grid, prop)

        elipsoide = self.params['ellipsoidinput']['value']
        elipsoide_split = elipsoide.split()

        range1 = float(elipsoide_split[0])
        range2 = float(elipsoide_split[1])
        range3 = float(elipsoide_split[2])

        azimuth = float(elipsoide_split[3])
        dip = float(elipsoide_split[4])
        rake = float(elipsoide_split[5])

        X, Y, Z = anis_search(X, Y, Z, range1, range2, range3, azimuth, dip,
                              rake)

        #Creates a list of all rock types
        rt_list = []
        for i in RT:
            if i not in rt_list and not math.isnan(i):
                rt_list.append(i)

        #Sort the rock type list in crescent order
        rt_list = [int(x) for x in rt_list]
        rt_list.sort()

        #Create a empty distance matrix
        dist_matrix = np.zeros(shape=((len(rt_list)), (len(RT))))

        #Calculates the signed distances, and append it in the distance matrix
        for i in range(len(rt_list)):
            rock = rt_list[i]

            for j in range(len(RT)):

                if math.isnan(RT[j]):
                    dist_matrix[i][j] = float('nan')

                elif RT[j] == rock:
                    dsmin = 1.0e21

                    for k in range(len(RT)):

                        if RT[j] != RT[k] and not math.isnan(RT[k]):
                            if (dist(X[j], Y[j], Z[j], X[k], Y[k],
                                     Z[k])) < dsmin:
                                dsmin = (dist(X[j], Y[j], Z[j], X[k], Y[k],
                                              Z[k]))

                        dist_matrix[i][j] = -dsmin

                else:
                    dsmin = 1.0e21

                    for k in range(len(RT)):

                        if RT[k] == rock:
                            if (dist(X[j], Y[j], Z[j], X[k], Y[k],
                                     Z[k])) < dsmin:
                                dsmin = (dist(X[j], Y[j], Z[j], X[k], Y[k],
                                              Z[k]))

                        dist_matrix[i][j] = dsmin

        #Creates the signed distances properties
        lst_props_grid = sgems.get_property_list(grid)

        for k in range(len(dist_matrix)):
            prop_final_data_name = 'Signed_Distances_RT_' + str(rt_list[k])

            if (prop_final_data_name in lst_props_grid):
                flag = 0
                i = 1
                while (flag == 0):
                    test_name = prop_final_data_name + '-' + str(i)
                    if (test_name not in lst_props_grid):
                        flag = 1
                        prop_final_data_name = test_name
                    i = i + 1

            list = dist_matrix[k].tolist()
            sgems.set_property(grid, prop_final_data_name, list)

        return True
Example #24
0
Need to install python module pyevtk;
In this file, direction data is exported as vector to be visulized at Paraview (after Glyph filter)
The output file goes to SGeMS main folder as "points.vtu"
"""

import numpy as np
import sgems
from pyevtk.hl import pointsToVTK

# Input properties (NEED TO INPUT grid name, direction data and ratio for coloring)
grid = "grid1"
direction_data = "05strike"
ratio_data = "05ratio"

# Initializing
prop = sgems.get_property(grid, direction_data)
ratio = sgems.get_property(grid, ratio_data)

propX = sgems.get_property(grid, "_X_")
propY = sgems.get_property(grid, "_Y_")
propZ = sgems.get_property(grid, "_Z_")
npoints = len(propX)

x = np.array(propX)
y = np.array(propY)
z = np.array(propZ)
vx = np.zeros(npoints)
vy = np.zeros(npoints)
vz = np.zeros(npoints)
rang = np.zeros(npoints)
Need to install python module pyevtk;
In this file,data is exported as points to be visulized at Paraview
The output file goes to SGeMS main folder as "points.vtu"
"""

import numpy as np 
import sgems
from pyevtk.hl import pointsToVTK


# Input properties (NEED TO INPUT grid object name and property name)
grid = "walker"
point_data = "V"

# Initializing
prop = sgems.get_property(grid,point_data)

propX = sgems.get_property(grid,"_X_")
propY = sgems.get_property(grid,"_Y_")
propZ = sgems.get_property(grid,"_Z_")
npoints = len(propX)

x = np.array(propX)
y = np.array(propY)
z = np.array(propZ)
output = np.array(prop)

# Output
pointsToVTK("./points", x, y, z, data = {point_data : output})

print "Done"
Example #26
0
    def execute(self):

        #Execute the function read_params
        read_params(self.params)
        print self.params

        # ----------------------------------------------------------------------
        #
        # Cut-offs domaining
        #
        # ----------------------------------------------------------------------

        # checking if box is checked
        if self.params['cutoff_check_box']['value'] == str(1):

            # Getting variables
            prop = self.params['prop_cutoff']['property']
            grid_d = self.params['prop_cutoff']['grid']
            cutoffs_user = (self.params['cutoffs_user']['value']).split()
            prop_cutoff = sgems.get_property(grid_d, prop)

            # substituting commas for points in users inputed cutoffs
            cutoffs_user_no_comma = []
            for i in cutoffs_user:
                cutoffs_user_no_comma.append(float(i.replace(",", ".")))

            coded_dataset = sample_class_cutoff(prop_cutoff, cutoffs_user_no_comma)

            # setting the variable
            prop_final_data_name = 'coded_cutoff_'+self.params['prop_cutoff']['property']
            lst_props_grid = sgems.get_property_list(grid_d)

            if (prop_final_data_name in lst_props_grid):
                flag = 0
                i = 1
                while (flag == 0):
                    test_name = prop_final_data_name + '-' + str(i)
                    if (test_name not in lst_props_grid):
                        flag = 1
                        prop_final_data_name = test_name
                    i = i + 1

            sgems.set_property(grid_d, prop_final_data_name, coded_dataset)

        # ----------------------------------------------------------------------
        #
        # K-means clustering
        #
        # ----------------------------------------------------------------------

        # checking if box is checked
        if self.params['k_check_box']['value'] == str(1):

            # Getting variables
            grid_k = self.params['K_grid']['value']
            nclus = int(self.params['k_number']['value'])
            sec_props_k = (self.params['k_sec_var']['value']).split(';')
            prim_var_k = self.params['K_prim_var']['value']

            var_isotopic_kmeans, nan_indices = isotopic_dataset(grid_k, prim_var_k, sec_props_k)

            #runing kmeans
            k = KMeans(n_clusters=nclus).fit(var_isotopic_kmeans)
            RT = k.labels_

            RT_lst = []
            m=0
            for i in range(len(nan_indices)+len(RT)):
                check = True
                for j in nan_indices:
                    if i == j:
                        RT_lst.append(float('nan'))
                        check = False
                if check == True:
                    RT_lst.append(RT[m])
                    m = m+1

            create_variable(grid_k, 'KMeans', RT_lst)

        # ----------------------------------------------------------------------
        #
        # Hierarchical clustering
        #
        # ----------------------------------------------------------------------

        # checking if box is checked
        if self.params['hier_check_box']['value'] == str(1):

            # Getting variables
            grid_h = self.params['hier_grid']['value']
            sec_props_h = (self.params['hier_sec_var']['value']).split(';')
            prim_var_h = self.params['hier_prim_var']['value']
            criterion = self.params['criterion']['value']
            treshold = float(self.params['treshold']['value'])
            method_h = self.params['method']['value']
            dist_metric = self.params['dist_met']['value']

            var_isotopic_hier, nan_indices_h = isotopic_dataset(grid_h, prim_var_h, sec_props_h)

            # generate the linkage matrix
            Z = linkage(var_isotopic_hier, method = method_h, metric = dist_metric)

            df = pd.DataFrame(Z)
            df.to_csv('linkage_matrix.csv', index = False)

            plt.figure(figsize=(20,20))
            dn = dendrogram(Z)
            plt.savefig('dendogram.png')

            #printing cophenet corr.
            c, coph_dists = cophenet(Z, pdist(var_isotopic_hier))
            print "Cophenet correlation should be close to 1 : {}".format(c)

            #runnig hierarchical clustering
            try:
                RT_lst_h = fcluster(Z, treshold, criterion= criterion)
            except:
                print 'erro'

            RT_lst_h_final = []
            m = 0
            for i in range(len(nan_indices_h) + len(RT_lst_h)):
                check = True
                for j in nan_indices_h:
                    if i == j:
                        RT_lst_h_final.append(float('nan'))
                        check = False
                if check == True:
                    RT_lst_h_final.append(RT_lst_h[m])
                    m = m + 1

            create_variable(grid_h, 'Hierarchical', RT_lst_h_final)

        # ----------------------------------------------------------------------
        #
        # GMM clustering
        #
        # ----------------------------------------------------------------------

        # checking if box is checked
        if self.params['gmm_checkbox']['value'] == str(1):

            # getting variables
            grid_gmm = self.params['gmm_grid']['value']
            prim_var_gmm = self.params['gmm_prim']['value']
            sec_gmm = (self.params['gmm_sec']['value']).split(';')
            components = int(self.params['gmm_components']['value'])
            cov_type = self.params['cov_type']['value']

            var_isotopic_gmm, nan_indices_gmm = isotopic_dataset(grid_gmm, prim_var_gmm, sec_gmm)

            gmm = GMM(n_components = components, covariance_type= cov_type).fit(var_isotopic_gmm)

            RT_lst_gmm = gmm.predict(var_isotopic_gmm)

            probs = gmm.predict_proba(var_isotopic_gmm)
            probs_trans = probs.T

            RT_lst_gmm_final = []
            m = 0
            for i in range(len(nan_indices_gmm) + len(RT_lst_gmm)):
                check = True
                for j in nan_indices_gmm:
                    if i == j:
                        RT_lst_gmm_final.append(float('nan'))
                        check = False
                if check == True:
                    RT_lst_gmm_final.append(RT_lst_gmm[m])
                    m = m + 1

            create_variable(grid_gmm, 'GMM', RT_lst_gmm_final)

            for i,j in enumerate(probs_trans):
                RT_lst_gmm_probs = []
                m = 0
                for k in range(len(nan_indices_gmm) + len(RT_lst_gmm)):
                    check = True
                    for l in nan_indices_gmm:
                        if k == l:
                            RT_lst_gmm_probs.append(float('nan'))
                            check = False
                    if check == True:
                        RT_lst_gmm_probs.append(probs_trans[i][m])
                        m = m + 1

                create_variable(grid_gmm, 'GMM_prob_cluster_'+str(i), RT_lst_gmm_probs)

        return True
Simple way to export SGeMS data to Paraview;
Need to install python module pyevtk;
In this file, data is exported as structured grid to be visulized at Paraview
The output file goes to SGeMS main folder as '.vtu'
"""


from pyevtk.hl import gridToVTK 
import numpy as np 
import sgems

# Parameters (NEED TO INPUT grid name and property name)
g = "grid1"
p = "30strike"

prop = sgems.get_property(g,p)

# Grid parameters (NEED TO INPUT lx, ly and lz as the dimensions of the grid)
nd = sgems.get_dims(g)
ox, oy, oz = 0.0, 0.0, 0.0
lx, ly, lz = 260.0, 300.0, 1.0 
dx, dy, dz = lx/nd[0], ly/nd[1], lz/nd[2] 
ncells = nd[0] * nd[1] * nd[2] 
npoints = (nd[0] + 1) * (nd[1] + 1) * (nd[2] + 1) 

# Coordinates 
x = np.arange(ox, ox + lx + 0.1*dx, dx, dtype='float64') 
y = np.arange(oy, oy + ly + 0.1*dy, dy, dtype='float64') 
z = np.arange(oz, oz + lz + 0.1*dz, dz, dtype='float64') 

# Writing output
    def execute(self):

	'''
		HSCATTERPLOT 
		_____________________________________________________________________________

		This is a template for SGems program variogram and covariance maps.
		The user have to fill the parameters with a ui.file with same name of this python 
		file before start program. The QT userinterface connect SGems data with this routine
		using the class params.
		
		The output of this program is a graphic demonstranting interpolated variogram values 
		along one plane 

	AUTHOR: DAVID ALVARENGA DRUMOND 		2016
	
	'''	

	'''
	INITIAL PARAMETERS 
	______________________________________________________________________________

	All initial parameters are transcribe by ui.file interface. Variables are choose 
	among common variables. The follow variables are:

	COMMON VARIABLES: 

	head_property= head property 
	head_grid = head grid 
	tail_property = tail property 
	tail_grid= tail grid 
	C_variogram = check box for variogram maps 
	C_covariance= check box for covariance maps 
	nlags= number of lags in experimental variogram 
	lagdistance = lag length for this experimental variograms 
	lineartolerance= linear tolerance for this map
	htolerance = horizontal tolerance for this map 
	vtolerance = vertical tolerance for this lag
	hband = horizontal band 
	vband = vertical band 
	dip = dip of the rake of variogram map 
	azimute = azimuth of the rake of variogram map
	gdiscrete = number of cells to discretize map 
	ncontour = number of contourn lines to interpolate in map 

	
	'''


	# Stabilish initial parameters 

	head_property= self.params['head_prop']['property']
	head_grid = self.params['head_prop']['grid']
	tail_property = self.params['tail_prop']['property']
	tail_grid= self.params['tail_prop']['grid']
	nlags= int(self.params['nlags']['value'])
	lagdistance = float(self.params['lagdistance']['value'])
	lineartolerance= float(self.params['lineartolerance']['value'])
	htolerance = float(self.params['htolangular']['value'])
	vtolerance = float(self.params['vtolangular']['value'])
	hband = float(self.params['hband']['value'])
	vband = float(self.params['vband']['value'])
	Dip = float(self.params['Dip']['value'])
	Azimute= float(self.params['Azimute']['value'])

	print (self.params)
	
	# Get values from SGems and exclude nan values  
	
	xh = []
	yh = []
	zh = [] 
	vh = []
	
	xh1 = sgems.get_property(head_grid, "_X_")
	yh1 = sgems.get_property(head_grid, "_Y_")
	zh1 = sgems.get_property(head_grid, "_Z_")
	vh1 = sgems.get_property(head_grid, head_property)	

	xh, yh, zh, vh = retire_nan(xh1,yh1,zh1,vh1)


	xt = []
	yt = []
	zt = []	
	vt = []

	xt1 = sgems.get_property(tail_grid, "_X_")
	yt1 = sgems.get_property(tail_grid, "_Y_")
	zt1 = sgems.get_property(tail_grid, "_Z_")
	vt1 = sgems.get_property(tail_grid, tail_property)

	xt, yt, zt, vt = retire_nan(xt1,yt1,zt1,vt1)	

	# Verify number of dimensions of problem
	
	# Verify dimensions of head 

	cdimensaoxh = False
	cdimensaoyh = False
	cdimensaozh = False

	for x in range(0,len(xh)):
		if (xh[x] != 0):
			cdimensaoxh = True


	for y in range(0,len(yh)):
		if (yh[y] != 0):
			cdimensaoyh = True


	for z in range(0,len(zh)):
		if (zh[z] != 0):
			cdimensaozh = True

	# Verify dimensions of tail 

	cdimensaoxt = False
	cdimensaoyt = False
	cdimensaozt = False

	for x in range(0,len(xt)):
		if (xt[x] != 0):
			cdimensaoxt = True

	for y in range(0,len(yt)):
		if (yt[y] != 0):
			cdimensaoyt = True


	for z in range(0,len(zt)):
		if (zt[z] != 0):
			cdimensaozt = True

	if ((cdimensaoxt == cdimensaoxh) and (cdimensaoyt == cdimensaoyh) and (cdimensaozt == cdimensaozh)):
		


		# Define maximum distance permissible 
		
		dmaximo = (nlags + 0.5)*lagdistance
		
		# Define tolerances if they are zero 
 
		if (htolerance == 0):
			htolerance= 45
		if (vtolerance == 0):
			vtolerance = 45
		if (hband == 0):
			hband = lagdistance/2
		if (vband == 0):
			vband = lagdistance/2
		if (lagdistance == 0):		
			lagdistance = 100
		if (lineartolerance == 0):
			lineartolerance = lagdistance/2
		
		
		
	
		# Convert tolerances in radians 

		htolerance = math.radians(htolerance)
		vtolerance = math.radians(vtolerance)	

		# Determine dip and azimuth projections  
		htolerance = math.cos(htolerance)
		vtolerance = math.cos(vtolerance)
	
		# Define all euclidian distances permissible 
		
		cabeca = []
		rabo = []
		distanciah =[]	
		distanciaxy =[]	
		distanciax =[]
		distanciay = []
 		distanciaz = []
		for t in range(0, len(yt)):
			for h in range(t, len(yh)):
				cabeca.append(vh[h])
				rabo.append(vt[t])
				dx = xh[h]-xt[t] 				
				dy= yh[h]-yt[t]
				dz = zh[h]-zt[t]
				if (distanciah > 0):
					distanciay.append(dy)
					distanciax.append(dx)
					distanciaz.append(dz)
					distanciah.append(math.sqrt(math.pow(dy,2) + math.pow(dx,2) + math.pow(dz,2)))						
					distanciaxy.append(math.sqrt(math.pow(dy,2) + math.pow(dx,2)))

		# Calculate all cos and sin values 		
	
		cos_Azimute = math.cos(math.radians(90-Azimute))
		sin_Azimute = math.sin(math.radians(90-Azimute))
		sin_Dip = math.sin(math.radians(90-Dip))
		cos_Dip = math.cos(math.radians(90-Dip))
	
		v_valores_admissiveis_h =[]
		v_valores_admissiveis_t =[]
		

		# Calculate admissible points  
			

		for l in range(0, nlags):			
			valores_admissiveis_h = []
			valores_admissiveis_t = []
			lag= lagdistance*(l+1)
			for p in range(0,len(distanciah)):
				if (distanciah[p] < dmaximo):
					limitemin = lag - lineartolerance
					limitemax = lag + lineartolerance
					if (distanciah[p] > limitemin and distanciah[p] < limitemax):					
						if (distanciaxy[p] > 0.000): 				
							check_azimute = (distanciax[p]*cos_Azimute +distanciay[p]*sin_Azimute)/distanciaxy[p]
						else:
							check_azimute = 1
						check_azimute = math.fabs(check_azimute)
						if (check_azimute >= htolerance):							
							check_bandh = (cos_Azimute*distanciay[p]) - (sin_Azimute*distanciax[p])
							check_bandh = math.fabs(check_bandh)
							if (check_bandh < hband):							
								if(distanciah[p] > 0.000):
									check_dip = (math.fabs(distanciaxy[p])*sin_Dip + distanciaz[p]*cos_Dip)/distanciah[p]
								else:
									check_dip = 0.000
								check_dip = math.fabs(check_dip) 
								if (check_dip >= vtolerance):
									check_bandv = sin_Dip*distanciaz[p] - cos_Dip*math.fabs(distanciaxy[p])
									check_bandv = math.fabs(check_bandv)
									if (check_bandv < vband):
										if (check_dip <0 and check_azimute <0):
											valores_admissiveis_h.append(rabo[p])
											valores_admissiveis_t.append(cabeca[p])
										else:
											valores_admissiveis_h.append(cabeca[p])
											valores_admissiveis_t.append(rabo[p])	
			if (len(valores_admissiveis_h) > 0 and len(valores_admissiveis_t) > 0):				
				v_valores_admissiveis_h.append(valores_admissiveis_h)
				v_valores_admissiveis_t.append(valores_admissiveis_t)
		
		


		for i in range(0,len(v_valores_admissiveis_h)):
			vh = []
			vt = []
			vh = np.array(v_valores_admissiveis_h[i])
			vt = np.array(v_valores_admissiveis_t[i])
			arquivo2 = open("./ar2gems/bin/plugins/Geostat/python/plot/saida_hscatter.txt","w")
			arquivo2.write(str(i)+"\n")
			arquivo2.write(str(lagdistance)+"\n")
			for j in range(0,len(vh)):
				arquivo2.write(str(vh[j])+"	"+str(vt[j])+"\n")
			arquivo2.close()
			os.system("python ./ar2gems/bin/plugins/Geostat/python/plot/plot_hscatter.py")
	

		
	
					
    	return True 
Example #29
0
    def execute(self):


	'''
		VARMAP 
		_____________________________________________________________________________

		This is a template for SGems program variogram and covariance maps.
		The user have to fill the parameters with a ui.file with same name of this python 
		file before start program. The QT userinterface connect SGems data with this routine
		using the class params.
		
		The output of this program is a graphic demonstranting interpolated variogram values 
		along one plane 

	AUTHOR: DAVID ALVARENGA DRUMOND 		2016
	
	'''	

	'''
	INITIAL PARAMETERS 
	______________________________________________________________________________

	All initial parameters are transcribe by ui.file interface. Variables are choose 
	among common variables. The follow variables are:

	COMMON VARIABLES: 

	head_property= head property 
	head_grid = head grid 
	tail_property = tail property 
	tail_grid= tail grid 
	C_variogram = check box for variogram maps 
	C_covariance= check box for covariance maps 
	nlags= number of lags in experimental variogram 
	lagdistance = lag length for this experimental variograms 
	lineartolerance= linear tolerance for this map
	htolerance = horizontal tolerance for this map 
	vtolerance = vertical tolerance for this lag
	hband = horizontal band 
	vband = vertical band 
	dip = dip of the rake of variogram map 
	azimute = azimuth of the rake of variogram map
	gdiscrete = number of cells to discretize map 
	ncontour = number of contourn lines to interpolate in map 

	
	'''

	# Stabilish initial parameters 

	head_property= self.params['head_prop']['property']
	head_grid = self.params['head_prop']['grid']
	tail_property = self.params['tail_prop']['property']
	tail_grid= self.params['tail_prop']['grid']
	C_variogram = int(self.params['C_variogram']['value'])
	C_covariance= int(self.params['C_covariance']['value'])
	nlags= int(self.params['nlags']['value'])
	lagdistance = float(self.params['lagdistance']['value'])
	lineartolerance= float(self.params['lineartolerance']['value'])
	htolerance = float(self.params['htolangular']['value'])
	vtolerance = float(self.params['vtolangular']['value'])
	hband = float(self.params['hband']['value'])
	vband = float(self.params['vband']['value'])
	dip = float(self.params['Dip']['value'])
	azimute = float(self.params['Azimute']['value'])
	gdiscrete = float(self.params['Gdiscrete']['value'])
	ncontour = int(self.params['ncontour']['value'])
	
	# Get values from sgems properties 

	xh = []
	yh = []
	zh = [] 
	vh = []
	
	xh1 = sgems.get_property(head_grid, "_X_")
	yh1 = sgems.get_property(head_grid, "_Y_")
	zh1 = sgems.get_property(head_grid, "_Z_")
	vh1 = sgems.get_property(head_grid, head_property)	

	xh, yh, zh, vh = retire_nan(xh1,yh1,zh1,vh1)


	xt = []
	yt = []
	zt = []	
	vt = []

	xt1 = sgems.get_property(tail_grid, "_X_")
	yt1 = sgems.get_property(tail_grid, "_Y_")
	zt1 = sgems.get_property(tail_grid, "_Z_")
	vt1 = sgems.get_property(tail_grid, tail_property)

	xt, yt, zt, vt = retire_nan(xt1,yt1,zt1,vt1)		

	# Verify dimensions 
	
	# Verify dimensions of head 

	cdimensaoxh = False
	cdimensaoyh = False
	cdimensaozh = False

	for x in range(0,len(xh)):
		if (xh[x] != 0):
			cdimensaoxh = True


	for y in range(0,len(yh)):
		if (yh[y] != 0):
			cdimensaoyh = True


	for z in range(0,len(zh)):
		if (zh[z] != 0):
			cdimensaozh = True

	# Verify dimensions of tail 

	cdimensaoxt = False
	cdimensaoyt = False
	cdimensaozt = False

	for x in range(0,len(xt)):
		if (xt[x] != 0):
			cdimensaoxt = True

	for y in range(0,len(yt)):
		if (yt[y] != 0):
			cdimensaoyt = True


	for z in range(0,len(zt)):
		if (zt[z] != 0):
			cdimensaozt = True

	if ((cdimensaoxt == cdimensaoxh) and (cdimensaoyt == cdimensaoyh) and (cdimensaozt == cdimensaozh)):
		


		# Define maximum distance permisible 
		
		dmaximo = (nlags + 0.5)*lagdistance
		
		# Transform tolerances if they are zero 

		if (htolerance == 0):
			htolerance= 45
		if (vtolerance == 0):
			vtolerance = 45
		if (hband == 0):
			hband = lagdistance/2
		if (vband == 0):
			vband = lagdistance/2
		if (lagdistance == 0):		
			lagdistance = 100
		if (lineartolerance == 0):
			lineartolerance = lagdistance/2
		
		
		
	
		# Convert tolerances in radians 
		htolerance = math.radians(htolerance)
		vtolerance = math.radians(vtolerance)	

		# Determine dip and azimuth projections 
		htolerance = math.cos(htolerance)
		vtolerance = math.cos(vtolerance)
	
		# Define all euclidian distances 
		
		cabeca = []
		rabo = []
		cabeca2 =[]
		rabo2 = []
		distanciah =[]	
		distanciaxy =[]	
		distanciax =[]
		distanciay = []
 		distanciaz = []
		for t in range(0, len(yt)):
			for h in range(t, len(yh)):
				cabeca.append(vh[h])
				rabo.append(vt[t])
				cabeca2.append(vt[h])
				rabo2.append(vh[t])
				dx = xh[h]-xt[t] 				
				dy= yh[h]-yt[t]
				dz = zh[h]-zt[t]
				if (distanciah > 0):
					distanciay.append(dy)
					distanciax.append(dx)
					distanciaz.append(dz)
					distanciah.append(math.sqrt(math.pow(dy,2) + math.pow(dx,2) + math.pow(dz,2)))						
					distanciaxy.append(math.sqrt(math.pow(dy,2) + math.pow(dx,2)))
		
		# Calculate all cosine and sine values 	
		

		cos_Azimute = []
		sin_Azimute = []
		cos_Dip = []
		sin_Dip = []
		flutuante_d = 0
		
		
		for a in range(0,360,10):
			diferenca = a + azimute 
			cos_Azimute.append(math.cos(math.radians(90-diferenca)))
			sin_Azimute.append(math.sin(math.radians(90-diferenca)))
			if (dip != 90 and dip != 180):
				flutuante_d = math.cos(math.radians(90) - math.fabs(math.atan(math.tan(math.radians(dip))*math.sin(math.radians(90-diferenca)))))
				cos_Dip.append(flutuante_d)
				flutuante_d = math.sin(math.radians(90) - math.fabs(math.atan(math.tan(math.radians(dip))*math.sin(math.radians(90-diferenca)))))
				sin_Dip.append(flutuante_d)
			else:	
				cos_Dip.append(1)
				sin_Dip.append(0)
	
		distancias_admissiveis = []
		azimute_admissiveis = []
		dip_admissiveis =[]
		v_valores_admissiveis_h =[]
		v_valores_admissiveis_t =[]
		v_valores_admissiveis_h2 =[]
		v_valores_admissiveis_t2 =[]
		pares = []		

		# Calculate permissible experimental pairs 

		for a in range(0,36):
			azm = math.radians(a*10)
			if (dip != 90 and dip != 180):
				dipatua = math.radians(90) - math.atan(math.tan(math.radians(dip))*math.sin(math.radians(90-diferenca)))
			else:
				dipatua = math.radians(90)
			for l in range(0, nlags):			
				valores_admissiveis_h = []
				valores_admissiveis_t = []
				valores_admissiveis_h2 =[]
				valores_admissiveis_t2 =[]
				distancia_admissivel = []
				azimute_admissivel =[]
				dip_admissivel=[]
				lag= lagdistance*(l+1)
				par= 0 
				for p in range(0,len(distanciah)):
					if (distanciah[p] < dmaximo):
						limitemin = lag - lineartolerance
						limitemax = lag + lineartolerance
						if (distanciah[p] > limitemin and distanciah[p] < limitemax):						
							if (distanciaxy[p] > 0.000): 				
								check_azimute = (distanciax[p]*cos_Azimute[a] +distanciay[p]*sin_Azimute[a])/distanciaxy[p]
							else:
								check_azimute = 1
							check_azimute = math.fabs(check_azimute)
							if (check_azimute >= htolerance):								
								check_bandh = (cos_Azimute[a]*distanciay[p]) - (sin_Azimute[a]*distanciax[p])
								check_bandh = math.fabs(check_bandh)
								if (check_bandh < hband):								
									if(distanciah[p] > 0.000):
										check_dip = (math.fabs(distanciaxy[p])*sin_Dip[a] + distanciaz[p]*cos_Dip[a])/distanciah[p]
									else:
										check_dip = 0.000
									check_dip = math.fabs(check_dip) 
									if (check_dip >= vtolerance):
										check_bandv = sin_Dip[a]*distanciaz[p] - cos_Dip[a]*math.fabs(distanciaxy[p])
										check_bandv = math.fabs(check_bandv)
										if (check_bandv < vband):
											if (check_dip < 0 and check_azimute < 0):
													valores_admissiveis_h.append(rabo[p])
													valores_admissiveis_t.append(cabeca[p])
													valores_admissiveis_h2.append(rabo2[p])
													valores_admissiveis_t2.append(cabeca2[p])
													distancia_admissivel.append(distanciah[p])
													par = par + 1	
													azimute_admissivel.append(azm)
													dip_admissivel.append(dipv)	
											else:
													valores_admissiveis_h.append(cabeca[p])
													valores_admissiveis_t.append(rabo[p])
													valores_admissiveis_h2.append(cabeca2[p])
													valores_admissiveis_t2.append(rabo2[p])
													distancia_admissivel.append(distanciah[p])
													par = par + 1	
													azimute_admissivel.append(azm)
													dip_admissivel.append(dipatua)		
				if (len(valores_admissiveis_h) > 0 and len(valores_admissiveis_t) > 0):	
					if (par > 0):		
						v_valores_admissiveis_h.append(valores_admissiveis_h)
						v_valores_admissiveis_h2.append(valores_admissiveis_h2)
						v_valores_admissiveis_t2.append(valores_admissiveis_t2)
						v_valores_admissiveis_t.append(valores_admissiveis_t)
						distancias_admissiveis.append(distancia_admissivel)
						pares.append(par)
						azimute_admissiveis.append(azimute_admissivel)	
						dip_admissiveis.append(dip_admissivel)
		

		# Calculate continuity functions 	

		# Variogram 
		
		if (C_variogram == 1): 		
			continuidade =[]
			lag_adm =[]
			azimute_adm =[]
			dip_adm =[]
			for i in range(0,len(v_valores_admissiveis_h)):
				flutuantet =[]
				flutuanteh =[]
				flutuanteh2 = []
				flutuantet2 =[]
				flutuanted =[]
				flutuantea=[]
				flutuantedip=[]
				par_var = 0
				flutuanteh = v_valores_admissiveis_h[i][:]
				flutuanteh2= v_valores_admissiveis_h2[i][:]
				flutuantet = v_valores_admissiveis_t[i][:]
				flutuantet2 = v_valores_admissiveis_t2[i][:]
				flutuanted = distancias_admissiveis[i][:]
				flutuantea= azimute_admissiveis[i][:]
				flutuantedip = dip_admissiveis[i][:]
				par_var= pares[i]
				soma = 0
				lagmedio =0
				agmedio =0 
				dgmedio = 0
				for j in range(0, len(flutuanteh)):
					soma = soma + (flutuanteh[j] - flutuantet2[j])*(flutuanteh2[j]-flutuantet[j])/(2*pares[i])
				continuidade.append(soma)
				for z in range(0, len(flutuanted)):
					lagmedio = lagmedio + flutuanted[z]/len(flutuanted)
				lag_adm.append(lagmedio)
				for g in range(0, len(flutuantea)):
					agmedio = agmedio + flutuantea[g]/len(flutuantea)
				azimute_adm.append(agmedio)
				for t in range(0, len(flutuantedip)):
					dgmedio = dgmedio + flutuantedip[t]/len(flutuantedip)
				dip_adm.append(dgmedio)
				
			
			
		# Covariogram 
 
		if (C_covariance == 1): 		
			continuidade =[]
			lag_adm =[]
			azimute_adm =[]
			dip_adm =[]
			for i in range(0,len(v_valores_admissiveis_h)):
				flutuantet =[]
				flutuanteh =[]
				flutuanted =[]
				flutuantea=[]
				flutuantedip=[]
				par_var = 0
				flutuanteh = v_valores_admissiveis_h[i]
				flutuantet = v_valores_admissiveis_t[i]
				flutuanted = distancias_admissiveis[i]
				flutuantea= azimute_admissiveis[i]
				flutuantedip = dip_admissiveis[i]
				par_var= pares[i]
				soma = 0
				lagmedio =0
				agmedio =0 
				dgmedio = 0
				somah = 0
				somat = 0 
				mediah = 0
				mediat =0
				for d in range (0, len(flutuanteh)):
					somah = somah + flutuanteh[d]
				mediah = float(somah/len(flutuanteh))
				for t in range (0, len(flutuantet)):
					somat = somat + flutuantet[t]
				mediat = float(somat/len(flutuantet))
				for j in range(0, len(flutuanteh)):		
						soma = soma + float(((flutuanteh[j] - mediah)*(flutuantet[j] - mediat))/(par_var))
				continuidade.append(soma)
				for z in range(0, len(flutuanted)):
					lagmedio = lagmedio + flutuanted[z]/len(flutuanted)
				lag_adm.append(lagmedio)
				for g in range(0, len(flutuantea)):
					agmedio = agmedio + flutuantea[g]/len(flutuantea)
				azimute_adm.append(agmedio)
				for y in range(0, len(flutuantedip)):
					dgmedio = dgmedio + flutuantedip[y]/len(flutuantedip)
				dip_adm.append(dgmedio)
				
		
		
		
		
		# Plot variograms on map 
	
		
		x = np.array(lag_adm)*np.sin(np.array(azimute_adm))
		y = np.array(lag_adm)*np.cos(np.array(azimute_adm))



		Xi = np.linspace(-max(x)-lagdistance,max(x)+lagdistance,gdiscrete)
		Yi = np.linspace(-max(y)-lagdistance,max(y)+lagdistance,gdiscrete)

	

		#make the axes
		f = plt.figure()
		left, bottom, width, height= [0,0.1, 0.7, 0.7]
		ax  = plt.axes([left, bottom, width, height])
		pax = plt.axes([left, bottom, width, height],
				projection='polar',
				axisbg='none')
		
		pax.set_theta_zero_location("N")
		pax.set_theta_direction(-1)

		cax = plt.axes([0.8, 0, 0.05, 1])
		ax.set_aspect(1)
		ax.axis('Off')
	

		# grid the data.
		Vi = griddata((x, y), np.array(continuidade), (Xi[None,:], Yi[:,None]), method='cubic')	
		cf = ax.contourf(Xi,Yi,Vi, ncontour, cmap=plt.cm.jet)


		gradient = np.linspace(-max(continuidade),max(continuidade), math.fabs(2*max(continuidade)))
		gradient = np.vstack((gradient, gradient))
		cax.xaxis.set_major_locator(plt.NullLocator())
		cax.yaxis.tick_right()
		cax.imshow(gradient.T, aspect='auto', cmap=plt.cm.jet)

		plt.show()
		plt.close()
Example #30
0
import sgems

sgems.execute(
    'LoadObjectFromFile  D:/Users/jwhite/Projects/Broward/Geostats/SGEMS/Layer1_thk.sgems::s-gems'
)
data = sgems.get_property('Layer_Thk', 'Layer_1_thk NGVD_meters')
print data
Example #31
0
    def execute(self):
        head_property = self.params['head_prop']['property']
        head_grid = self.params['head_prop']['grid']

        tail_property = self.params['tail_prop']['property']
        tail_grid = self.params['tail_prop']['grid']

        #less_iqual = None
        #more_iqual = None
        cut_off = float(self.params['cut_off']['value'])
        new_prop = self.params['new_prop']['value']
        new_prop1 = self.params['new_prop1']['value']
        new_prop2 = self.params['new_prop2']['value']
        #mean = float(self.params['mean']['value'])
        #median = float(self.params['median']['value'])
        #variance = float(self.params['variance']['value'])
        fases = int(self.params['fases']['value'])
        simulation = int(self.params['simulation']['value'])
        runs = int(self.params['runs']['value'])
        #x = float(self.params['x']['value'])
        #y = float(self.params['y']['value'])
        #z = float(self.params['z']['value'])
        less_equal = self.params['rsless']['value']
        more_equal = self.params['rbgreater']['value']
        seeds = self.params['seeds']['value']
        seeds_ = map(int, seeds.strip().split(","))

        g = None
        ind = None
        w = None
        m = None
        datahist_global = None

        xgrid = sgems.get_property(head_grid, "_X_")
        ygrid = sgems.get_property(head_grid, "_Y_")
        zgrid = sgems.get_property(head_grid, "_Z_")
        grid_value = sgems.get_property(head_grid, head_property)
        r = sgems.get_dims(head_grid)

        xgrid1 = sgems.get_property(tail_grid, "_X_")
        ygrid1 = sgems.get_property(tail_grid, "_Y_")
        zgrid1 = sgems.get_property(tail_grid, "_Z_")
        n_ = sgems.get_property(tail_grid, tail_property)

        v_d = []  #value id
        l_c = []  #list cut off
        l_2 = []  #second list
        l_g = []  #global list reference_value
        h = 1

        n_rows = r[0]  #30#len(ygrid)
        n_cols = r[1]  #25#len(xgrid)
        n_levels = r[2]
        print "berthin", r, "n_", n_rows, n_cols, n_levels
        K = len(seeds_)
        matrix_dim = n_rows, n_cols

        def cut_off_(more_equal, less_equal):
            if (more_equal == '1' and less_equal == '0'):

                def w_o(cut_off):  #define waste ore in 0 and 1
                    for i in grid_value:
                        if i >= cut_off:
                            l_c.append(i)
                        else:
                            l_c.append(0)
                    return sgems.set_property(head_grid, new_prop, l_c), l_c
                    #return l_c

                w_o(cut_off)
            elif (more_equal == '0' and less_equal == '1'):

                def w_o_(cut_off):  #define waste as 0 and ore as grade
                    for i in grid_value:
                        if i <= cut_off:
                            l_c.append(i)
                        else:
                            l_c.append(0)
                    return sgems.set_property(head_grid, new_prop, l_c), l_c
                    #return l_c

                w_o_(cut_off)
            elif (more_equal == '0' and less_equal == '0'):
                print "Select option of cut off"
                self.dict_gen_params['execution_status'] = "ERROR"
            else:
                print "Error in execution type parameters"
                self.dict_gen_params['execution_status'] = "ERROR"

        grid1 = cut_off_(more_equal, less_equal)
        gridnt = l_c
        grid = np.array(gridnt).reshape(n_rows, n_cols, n_levels)

        plt_imshowN([grid, grid == 0, grid, grid == 0], [0, 0, 1, 1],
                    [dict(cmap='jet', interpolation='nearest')] * 4,
                    dim=(2, 2))
        """
        def cut_off_(grid_value, cut_off, more_equal, less_equal):
            more_equal, less_equal = map(int, [more_equal, less_equal])
            if more_equal + less_equal != 1:
                print 'Error, wrong cut_off values'
            else:
                if more_equal:
                    threshold = grid_value >= cut_off
                else:
                    threshold = grid_value <= cut_off
                return threshold * grid_value
        grid2 = cut_off_(grid_value, cut_off, more_equal, less_equal)
        print type(grid2), len(grid2)
        sgems.set_property(head_grid,new_prop,grid2)#print grid#plt_imshowN([head_grid, grid], [dict(cmap='jet', interpolation='nearest'), dict(cmap='jet', interpolation='nearest')], (1,2))
        """

        def quantil(p):
            return np.percentile(p, np.arange(0, 100, 5))

        def compare(s, h):
            c = []
            for i in s:
                for j in h:
                    if i + j > 0:
                        c.append(((i - j)**2) / (i + j))
            d = sum(c)
            return d

        def run_union_find(painter, K, iter_label, max_steps):
            fake_painter = copy.deepcopy(painter)
            fake_painter.paint_Kregions(K, iter_label, max_steps)
            y0 = np.ndarray.tolist((fake_painter.connected_processed_map *
                                    fake_painter.grid).ravel())
            c_global = quantil(gridnt)
            c_list = quantil(y0)
            return compare(c_global, c_list), fake_painter

        def search_best_run(painter, K, n_iterations, max_steps):
            best_cost = 10000000000
            best_painter = None
            for iter_label in xrange(n_iterations):
                cost, fake_painter = run_union_find(painter, K, iter_label,
                                                    max_steps)
                print 'iter', iter_label, 'cost', cost
                if cost < best_cost:
                    best_cost = cost
                    best_painter = fake_painter
            assert (best_painter != None)
            return (best_cost, best_painter)

        def repeat_all(grid, K, painter, n_iterations, n_steps_list, n_runs):
            for i, max_steps in zip(xrange(n_runs), n_steps_list):
                print i, "run"
                cost, painter = search_best_run(painter, K, n_iterations,
                                                max_steps)
                #plt_imshowN([painter.connected_map, painter.connected_map_ordem], [0, 0], [dict(cmap='jet', interpolation='nearest'), dict(cmap='jet')], dim=(1,2))
                plt_imshowN([
                    painter.connected_map * (painter.grid != 0),
                    painter.connected_map_ordem, painter.connected_map *
                    (painter.grid != 0), painter.connected_map_ordem
                ], [0, 0, 1, 1],
                            [dict(cmap='jet', interpolation='nearest')] * 4,
                            dim=(2, 2))
                #np.reshape(grid, (1,np.product(grid.shape)))
                maps_seed = (painter.connected_map * painter.connected_map)
                maps_seed_ = np.ndarray.tolist(
                    maps_seed.ravel())  #maps__ = np.array(maps_).T
                sgems.set_property(head_grid, new_prop1 + '-' + str(i),
                                   maps_seed_)
                maps_ = painter.connected_map_ordem
                maps__ = np.ndarray.tolist(maps_.ravel())
                #
                sgems.set_property(head_grid, new_prop2 + '-' + str(i), maps__)
                ee = np.ma.masked_array(grid, mask=maps_ == 0)
                ee_ = ee.filled(0)
                ee__ = np.ndarray.tolist(ee_.ravel())
                sgems.set_property(head_grid, "sect_maps" + '-' + str(i), ee__)

        uf = UnionFind(n_rows * n_cols * n_levels)
        guto = Painter(seeds_, grid, uf, K)
        repeat_all(grid,
                   K,
                   painter=guto,
                   n_iterations=simulation,
                   n_steps_list=[fases] * runs,
                   n_runs=runs)  #cambiando

        return True
Simple way to export SGeMS data to Paraview;
Need to install python module pyevtk;
In this file,data is exported as points to be visulized at Paraview
The output file goes to SGeMS main folder as "points.vtu"
"""

import numpy as np
import sgems
from pyevtk.hl import pointsToVTK

# Input properties (NEED TO INPUT grid object name and property name)
grid = "walker"
point_data = "V"

# Initializing
prop = sgems.get_property(grid, point_data)

propX = sgems.get_property(grid, "_X_")
propY = sgems.get_property(grid, "_Y_")
propZ = sgems.get_property(grid, "_Z_")
npoints = len(propX)

x = np.array(propX)
y = np.array(propY)
z = np.array(propZ)
output = np.array(prop)

# Output
pointsToVTK("./points", x, y, z, data={point_data: output})

print "Done"
Example #33
0
    def execute(self):

        #aqui vai o codigo
        #getting variables
        tg_grid_name = self.params['gridselector']['value']
        tg_region_name = self.params['gridselector']['region']
        tg_prop_name = self.params['lineEdit']['value']
        keep_variables = self.params['checkBox_2']['value']
        props_grid_name = self.params['gridselectorbasic']['value']
        var_names = self.params['orderedpropertyselector']['value'].split(';')
        codes = [v.split('_')[-1] for v in var_names]
        var_type = 'Signed Distances'

        variables = []
        nan_filters = []
        for v in var_names:
            values = np.array(sgems.get_property(props_grid_name, v))
            nan_filter = np.isfinite(values)
            filtered_values = values[nan_filter]
            nan_filters.append(nan_filter)
            variables.append(filtered_values)
        nan_filter = np.product(nan_filters, axis=0)
        nan_filter = nan_filter == 1

        x, y, z = np.array(sgems.get_X(props_grid_name))[nan_filter], np.array(
            sgems.get_Y(props_grid_name))[nan_filter], np.array(
                sgems.get_Z(props_grid_name))[nan_filter]

        #sim variables
        n_reals = int(self.params['spinBox']['value'])
        n_lines = int(self.params['spinBox_2']['value'])
        p_factor = float(self.params['doubleSpinBox']['value'])
        seed = int(self.params['spinBox_3']['value'])

        acceptance = [
            float(i) for i in self.params['lineEdit_2']['value'].split(',')
        ]
        if len(acceptance) == 1 and len(codes) > 1:
            acceptance = acceptance * len(codes)
        acceptance = np.array(acceptance)

        #getting variograms for interpolation
        print('Getting variogram models')

        use_model_file = self.params['checkBox']['value']
        if use_model_file == '1':
            path = self.params['filechooser']['value']
            variograms = helpers.modelfile_to_ar2gasmodel(path)
            if len(variograms) == 1:
                values_covs = list(variograms.values())
                varg_lst = values_covs * len(codes)
                variograms = {}
                variograms[0] = varg_lst[0]
        else:
            p = self.params
            varg_lst = helpers.ar2gemsvarwidget_to_ar2gascovariance(p)
            if len(varg_lst) == 0:
                variograms = {}
            if len(varg_lst) == 1:
                varg_lst = varg_lst * len(codes)
                variograms = {}
                variograms[0] = varg_lst[0]

            else:
                variograms = dict(zip(codes, varg_lst))

        #getting variograms for simulation
        use_model_file = self.params['checkBox_3']['value']
        if use_model_file == '1':
            path = self.params['filechooser_2']['value']
            sim_variograms = helpers.modelfile_to_ar2gasmodel(path)
            if len(variograms) == 1:
                values_covs = list(sim_variograms.values())
                varg_lst = values_covs * len(codes)
                sim_variograms = {}
                sim_variograms[0] = varg_lst[0]
        else:
            p = self.params
            varg_lst = helpers.ar2gemsvarwidget_to_ar2gascovariance_sim(p)
            if len(varg_lst) == 0:
                sim_variograms = {}
            if len(varg_lst) == 1:
                varg_lst = varg_lst * len(codes)
                sim_variograms = {}
                sim_variograms[0] = varg_lst[0]

            else:
                sim_variograms = dict(zip(codes, varg_lst))

        ids = [
            sgems.get_closest_nodeid(tg_grid_name, xi, yi, zi)
            for xi, yi, zi in zip(x, y, z)
        ]
        rt_prop = sd_to_cat(variables, codes)

        #interpolating variables
        num_models = []
        for idx in range(n_reals):
            print('Working on realization {}...'.format(idx + 1))

            tg_prop_name_temp = tg_prop_name + '_real_{}'.format(idx)

            perturbed_variables = perturb_sd(x, y, z, variables, codes,
                                             sim_variograms, seed, n_lines,
                                             p_factor)
            seed = seed + 1

            a2g_grid = helpers.ar2gemsgrid_to_ar2gasgrid(
                tg_grid_name, tg_region_name)

            interpolated_variables = interpolate_variables(
                x, y, z, perturbed_variables, codes, a2g_grid, variograms,
                keep_variables, var_type, tg_prop_name_temp, tg_grid_name)

            #creating a geologic model
            build_geomodel(var_type, interpolated_variables, codes, a2g_grid,
                           tg_grid_name, tg_prop_name_temp, ids, acceptance,
                           rt_prop, num_models)

        print('{} geologic models accepted!'.format(len(num_models)))
        print('Finished!')

        return True
Example #34
0
import sgems

mask=sgems.get_property('mask', 'facies')
porosity=sgems.get_property('kriging grid', 'estimated porosity')

for i in range(1,len(mask)) :
        if mask[i] == 0:
                porosity[i]= -9966699
sgems.set_property('kriging grid', 'estimated porosity', porosity )
    def execute(self):
        print self.params
        # ESTABELECA OS PARAMETROS INICIAIS
        head_property = self.params["head_prop"]["property"]
        head_grid = self.params["head_prop"]["grid"]
        tail_property = self.params["tail_prop"]["property"]
        tail_grid = self.params["tail_prop"]["grid"]
        C_variogram = int(self.params["C_variogram"]["value"])
        C_covariance = int(self.params["C_covariance"]["value"])
        nlags = int(self.params["nlags"]["value"])
        lagdistance = float(self.params["lagdistance"]["value"])
        lineartolerance = float(self.params["lineartolerance"]["value"])
        htolerance = float(self.params["htolangular"]["value"])
        vtolerance = float(self.params["vtolangular"]["value"])
        hband = float(self.params["hband"]["value"])
        vband = float(self.params["vband"]["value"])
        dip = float(self.params["Dip"]["value"])
        azimute = float(self.params["Azimute"]["value"])
        gdiscrete = float(self.params["Gdiscrete"]["value"])
        ncontour = int(self.params["ncontour"]["value"])
        Remove = float(self.params["Remove"]["value"])

        def retire_nan(x, y, z, v):
            xn = []
            yn = []
            zn = []
            vn = []
            for i in range(0, len(v)):
                if v[i] > -99999999999999999:

                    xn.append(x[i])
                    yn.append(y[i])
                    zn.append(z[i])
                    vn.append(v[i])
            return xn, yn, zn, vn

        xh = []
        yh = []
        zh = []
        vh = []

        xh1 = sgems.get_property(head_grid, "_X_")
        yh1 = sgems.get_property(head_grid, "_Y_")
        zh1 = sgems.get_property(head_grid, "_Z_")
        vh1 = sgems.get_property(head_grid, head_property)

        xh, yh, zh, vh = retire_nan(xh1, yh1, zh1, vh1)

        xt = []
        yt = []
        zt = []
        vt = []

        xt1 = sgems.get_property(tail_grid, "_X_")
        yt1 = sgems.get_property(tail_grid, "_Y_")
        zt1 = sgems.get_property(tail_grid, "_Z_")
        vt1 = sgems.get_property(tail_grid, tail_property)

        xt, yt, zt, vt = retire_nan(xt1, yt1, zt1, vt1)

        # VERIFIQUE O NUMERO DE DIMENSOES DO PROBLEMA

        # VERIFICACAO DAS DIMENSOES DO HEAD

        cdimensaoxh = False
        cdimensaoyh = False
        cdimensaozh = False

        for x in range(0, len(xh)):
            if xh[x] != 0:
                cdimensaoxh = True

        for y in range(0, len(yh)):
            if yh[y] != 0:
                cdimensaoyh = True

        for z in range(0, len(zh)):
            if zh[z] != 0:
                cdimensaozh = True

                # VERIFICACAO DAS DIMENSOES DO TAIL

        cdimensaoxt = False
        cdimensaoyt = False
        cdimensaozt = False

        for x in range(0, len(xt)):
            if xt[x] != 0:
                cdimensaoxt = True

        for y in range(0, len(yt)):
            if yt[y] != 0:
                cdimensaoyt = True

        for z in range(0, len(zt)):
            if zt[z] != 0:
                cdimensaozt = True

        if (cdimensaoxt == cdimensaoxh) and (cdimensaoyt == cdimensaoyh) and (cdimensaozt == cdimensaozh):

            # DEFINA A MAXIMA DISTANCIA PERMISSIVEL

            dmaximo = (nlags + 0.5) * lagdistance

            # CONVERTA TOLERANCIAS SE ELAS FOREM IGUAIS A ZERO
            if htolerance == 0:
                htolerance = 45
            if vtolerance == 0:
                vtolerance = 45
            if hband == 0:
                hband = lagdistance / 2
            if vband == 0:
                vband = lagdistance / 2
            if lagdistance == 0:
                lagdistance = 100
            if lineartolerance == 0:
                lineartolerance = lagdistance / 2

                # CONVERTA OS VALORES DE TOLERANCIA EM RADIANOS
            htolerance = math.radians(htolerance)
            vtolerance = math.radians(vtolerance)

            # DETERMINE AS PROJECOES DO DIP E DO AZIMUTE
            htolerance = math.cos(htolerance)
            vtolerance = math.cos(vtolerance)

            # TRANSFORME O DIP EM VALOR NEGATIVO PARA A ROTACAO DO PLANO
            dip = -dip

            xhrot = []
            yhrot = []
            zhrot = []
            xttrot = []
            yttrot = []
            zttrot = []

            for i in range(0, len(xh)):

                # ROTACIONE PRIMEIRAMENTE NO AZIMUTE

                xrot = math.cos(math.radians(azimute)) * xh[i] - math.sin(math.radians(azimute)) * yh[i]
                yrot = math.sin(math.radians(azimute)) * xh[i] + math.cos(math.radians(azimute)) * yh[i]
                yrot2 = math.cos(math.radians(dip)) * yrot - math.sin(math.radians(dip)) * zh[i]
                zrot = math.sin(math.radians(dip)) * yrot + math.cos(math.radians(dip)) * zh[i]

                xhrot.append(xrot)
                yhrot.append(yrot2)
                zhrot.append(zrot)

                # ROTACIONE EM SEGUIDA NO MERGULHO

                xtrot = math.cos(math.radians(azimute)) * xt[i] - math.sin(math.radians(azimute)) * yt[i]
                ytrot = math.sin(math.radians(azimute)) * xt[i] + math.cos(math.radians(azimute)) * yt[i]
                ytrot2 = math.cos(math.radians(dip)) * ytrot - math.sin(math.radians(dip)) * zt[i]
                ztrot = math.sin(math.radians(dip)) * ytrot + math.cos(math.radians(dip)) * zt[i]

                xttrot.append(xtrot)
                yttrot.append(ytrot2)
                zttrot.append(ztrot)

                # CONVERTA OS VALORES DE TOLERANCIA EM RADIANOS
            htolerance = math.radians(htolerance)
            vtolerance = math.radians(vtolerance)

            # DETERMINE AS PROJECOES DO DIP E DO AZIMUTE
            htolerance = math.cos(htolerance)
            vtolerance = math.cos(vtolerance)

            # DEFINA TODAS AS DISTANCIAS EUCLIDIANAS POSSIVEIS

            cabeca = []
            rabo = []
            cabeca2 = []
            rabo2 = []
            distanciah = []
            distanciaxy = []
            distanciax = []
            distanciay = []
            distanciaz = []
            for t in range(0, len(yt)):
                for h in range(t, len(yh)):

                    dx = xhrot[h] - xttrot[t]
                    dy = yhrot[h] - yttrot[t]
                    dz = zhrot[h] - zttrot[t]
                    dh = math.sqrt(math.pow(dy, 2) + math.pow(dx, 2) + math.pow(dz, 2))

                    if dh < dmaximo:
                        cabeca.append(vh[h])
                        cabeca2.append(vt[h])
                        rabo2.append(vt[t])
                        rabo.append(vh[t])

                        distanciay.append(dy)
                        distanciax.append(dx)
                        distanciaz.append(dz)
                        distanciah.append(dh)
                        distanciaxy.append(math.sqrt(math.pow(dy, 2) + math.pow(dx, 2)))

                        # CALCULE TODOS OS VALORES DE COS E SENO ADMISSIVEIS AO AZIMUTE

            cos_Azimute = []
            sin_Azimute = []
            flutuante_d = 0

            for a in range(0, 360, 20):
                diferenca = a
                cos_Azimute.append(math.cos(math.radians(90 - diferenca)))
                sin_Azimute.append(math.sin(math.radians(90 - diferenca)))
                cos_Dip = math.cos(math.radians(90))
                sin_Dip = math.sin(math.radians(90))

            distancias_admissiveis = []
            azimute_admissiveis = []
            dip_admissiveis = []
            v_valores_admissiveis_h = []
            v_valores_admissiveis_t = []
            v_valores_admissiveis_h2 = []
            v_valores_admissiveis_t2 = []
            pares = []

            # CALCULE OS PONTOS ADMISSIVEIS
            for a in xrange(0, 18):

                # reestabelca o valor do norte retirando novamente o azimute

                azm = math.radians(a * 20)
                if dip != 90 and dip != 180:
                    dipatua = math.radians(90) - math.atan(
                        math.tan(math.radians(dip)) * math.sin(math.radians(90 - azm))
                    )
                else:
                    dipatua = math.radians(90)
                for l in xrange(0, nlags):
                    valores_admissiveis_h = []
                    valores_admissiveis_t = []
                    valores_admissiveis_h2 = []
                    valores_admissiveis_t2 = []
                    distancia_admissivel = []
                    azimute_admissivel = []
                    dip_admissivel = []
                    lag = lagdistance * (l + 1)
                    par = 0
                    limitemin = lag - lineartolerance
                    limitemax = lag + lineartolerance
                    for p in xrange(0, len(distanciah)):
                        if distanciah[p] > limitemin and distanciah[p] < limitemax:
                            if distanciaxy[p] > 0.000:
                                check_azimute = (
                                    distanciax[p] * cos_Azimute[a] + distanciay[p] * sin_Azimute[a]
                                ) / distanciaxy[p]
                            else:
                                check_azimute = 1
                            check_azimute = math.fabs(check_azimute)
                            if check_azimute >= htolerance:
                                check_bandh = (cos_Azimute[a] * distanciay[p]) - (sin_Azimute[a] * distanciax[p])
                                check_bandh = math.fabs(check_bandh)
                                if check_bandh < hband:
                                    if distanciah[p] > 0.000:
                                        check_dip = (
                                            math.fabs(distanciaxy[p]) * sin_Dip + distanciaz[p] * cos_Dip
                                        ) / distanciah[p]
                                    else:
                                        check_dip = 0.000
                                    check_dip = math.fabs(check_dip)
                                    if check_dip >= vtolerance:
                                        check_bandv = sin_Dip * distanciaz[p] - cos_Dip * math.fabs(distanciaxy[p])
                                        check_bandv = math.fabs(check_bandv)
                                        if check_bandv < vband:
                                            valores_admissiveis_h.append(cabeca[p])
                                            valores_admissiveis_t.append(rabo[p])
                                            valores_admissiveis_h2.append(cabeca2[p])
                                            valores_admissiveis_t2.append(rabo2[p])
                                            distancia_admissivel.append(distanciah[p])
                                            par = par + 1
                                            azimute_admissivel.append(azm)
                                            dip_admissivel.append(dipatua)
                    if len(valores_admissiveis_h) > 0 and len(valores_admissiveis_t) > 0:
                        if par > 0:
                            v_valores_admissiveis_h.append(valores_admissiveis_h)
                            v_valores_admissiveis_h2.append(valores_admissiveis_h2)
                            v_valores_admissiveis_t2.append(valores_admissiveis_t2)
                            v_valores_admissiveis_t.append(valores_admissiveis_t)
                            distancias_admissiveis.append(distancia_admissivel)
                            pares.append(par)
                            azimute_admissiveis.append(azimute_admissivel)
                            dip_admissiveis.append(dip_admissivel)

                            # CALCULE AS FUNCOES DE CONTINUIDADE ESPACIAL SEGUNDO OS VALORES ADMISSIVEIS

                            # CALCULE O VARIOGRAMA

            if C_variogram == 1:
                continuidade = []
                lag_adm = []
                azimute_adm = []
                dip_adm = []
                for i in xrange(0, len(v_valores_admissiveis_h)):
                    flutuantet = []
                    flutuanteh = []
                    flutuanteh2 = []
                    flutuantet2 = []
                    flutuanted = []
                    flutuantea = []
                    flutuantedip = []
                    par_var = 0
                    flutuanteh = v_valores_admissiveis_h[i][:]
                    flutuanteh2 = v_valores_admissiveis_h2[i][:]
                    flutuantet = v_valores_admissiveis_t[i][:]
                    flutuantet2 = v_valores_admissiveis_t2[i][:]
                    flutuanted = distancias_admissiveis[i][:]
                    flutuantea = azimute_admissiveis[i][:]
                    flutuantedip = dip_admissiveis[i][:]
                    par_var = pares[i]
                    soma = 0
                    lagmedio = 0
                    agmedio = 0
                    dgmedio = 0
                    for j in xrange(0, len(flutuanteh)):
                        soma = soma + (flutuanteh[j] - flutuantet[j]) * (flutuanteh2[j] - flutuantet2[j]) / (
                            2 * pares[i]
                        )
                    for z in xrange(0, len(flutuanted)):
                        lagmedio = lagmedio + flutuanted[z] / len(flutuanted)
                    for g in xrange(0, len(flutuantea)):
                        agmedio = agmedio + flutuantea[g] / len(flutuantea)
                    for t in xrange(0, len(flutuantedip)):
                        dgmedio = dgmedio + flutuantedip[t] / len(flutuantedip)
                    if soma <= Remove:
                        dip_adm.append(dgmedio)
                        continuidade.append(soma)
                        azimute_adm.append(agmedio)
                        lag_adm.append(lagmedio)

                        # CALCULE O COVARIOGRAMA
            if C_covariance == 1:
                continuidade = []
                lag_adm = []
                azimute_adm = []
                dip_adm = []
                for i in xrange(0, len(v_valores_admissiveis_h)):
                    flutuantet = []
                    flutuanteh = []
                    flutuanted = []
                    flutuantea = []
                    flutuantedip = []
                    par_var = 0
                    flutuanteh = v_valores_admissiveis_h[i]
                    flutuantet = v_valores_admissiveis_t[i]
                    flutuanted = distancias_admissiveis[i]
                    flutuantea = azimute_admissiveis[i]
                    flutuantedip = dip_admissiveis[i]
                    par_var = pares[i]
                    soma = 0
                    lagmedio = 0
                    agmedio = 0
                    dgmedio = 0
                    somah = 0
                    somat = 0
                    mediah = 0
                    mediat = 0
                    for d in range(0, len(flutuanteh)):
                        somah = somah + flutuanteh[d]
                    mediah = float(somah / len(flutuanteh))
                    for t in range(0, len(flutuantet)):
                        somat = somat + flutuantet[t]
                    mediat = float(somat / len(flutuantet))
                    for j in xrange(0, len(flutuanteh)):
                        soma = soma + float(((flutuanteh[j] - mediah) * (flutuantet[j] - mediat)) / (par_var))
                    for z in xrange(0, len(flutuanted)):
                        lagmedio = lagmedio + flutuanted[z] / len(flutuanted)

                    for g in xrange(0, len(flutuantea)):
                        agmedio = agmedio + flutuantea[g] / len(flutuantea)

                    for y in xrange(0, len(flutuantedip)):
                        dgmedio = dgmedio + flutuantedip[y] / len(flutuantedip)
                    if soma <= Remove:
                        dip_adm.append(dgmedio)
                        continuidade.append(soma)
                        azimute_adm.append(agmedio)
                        lag_adm.append(lagmedio)

                        # PLOTE O MAPA DE VARIOGRAMAS INTERPOLADO

            x = np.array(lag_adm) * np.sin(np.array(azimute_adm))
            y = np.array(lag_adm) * np.cos(np.array(azimute_adm))

            maximo = 0
            if max(x) > max(y):
                maximo = max(x)
            else:
                maximo = max(y)

            Xi = np.linspace(-maximo, maximo, gdiscrete)
            Yi = np.linspace(-maximo, maximo, gdiscrete)

            # make the axes
            f = plt.figure()
            left, bottom, width, height = [0, 0.1, 0.7, 0.7]
            ax = plt.axes([left, bottom, width, height])
            pax = plt.axes([left, bottom, width, height], projection="polar", axisbg="none")

            pax.set_theta_zero_location("N")
            pax.set_theta_direction(-1)

            ax.set_aspect(1)
            ax.axis("Off")

            # grid the data.
            Vi = griddata((x, y), np.array(continuidade), (Xi[None, :], Yi[:, None]), method="linear")
            cf = ax.contourf(Xi, Yi, Vi, ncontour, cmap=plt.cm.jet)

            gradient = np.linspace(1, 0, 256)
            gradient = np.vstack((gradient, gradient))

            cax = plt.axes([0.7, 0.05, 0.05, 0.8])
            cax.xaxis.set_major_locator(plt.NullLocator())
            cax.yaxis.tick_right()
            cax.imshow(gradient.T, aspect="auto", cmap=plt.cm.jet)
            cax.set_yticks(np.linspace(0, 256, len(cf.get_array())))
            cax.set_yticklabels(map(str, cf.get_array())[::-1])

            plt.show()
            plt.close()
    def execute(self):
        dif = []
        Prop1 = sgems.get_property(self.params["GridName1"]["grid"], self.prop1)
        Prop2 = sgems.get_property(self.params["GridName2"]["grid"], self.prop2)

        dif2 = []
        for i in range(len(Prop1)):
            # 	  if(Prop1[i] != sgems.nan() and Prop2[i] != sgems.nan()):
            if math.isnan(Prop1[i]) == False and math.isnan(Prop2[i]) == False:
                dif.append((Prop1[i] - Prop2[i]) / Prop1[i])
            else:
                dif.append(sgems.nan())
        final_prop = "Deviation"
        lst = sgems.get_property_list(self.params["GridName1"]["grid"])
        if final_prop in lst:
            flag = 0
            i = 1
            while flag == 0:
                new_prop_name = final_prop + "_" + str(i)
                if new_prop_name not in lst:
                    flag = 1
                    final_prop = new_prop_name
                i = i + 1
        print final_prop
        # for i in range(len(Prop1)):
        # dif2.append((Prop1[i]+dif[i]))

        sgems.set_property(self.params["GridName1"]["grid"], final_prop, dif)
        # sgems.set_property(self.params["GridName2"]["grid"],"sum",dif2)
        PP = []
        a = float(self.cte)
        print a, self.cte
        for i in range(len(Prop2)):
            if self.check == "1":
                if self.radio1 == "1":
                    print Prop1[i], sgems.nan()
                    #  	      if(Prop1[i]==float(sgems.nan())):
                    if math.isnan(Prop1[i]) == True:
                        print "estou no laco i =", i,
                        PP.append(Prop2[i] + Prop2[i] * a)
                    else:
                        PP.append(Prop2[i])
                if self.radio2 == "1":
                    if math.isnan(Prop1[i]) == True:
                        PP.append(Prop2[i] - Prop2[i] * a)
                    else:
                        PP.append(Prop2[i])
        final_prop2 = "Post_process"
        lst2 = sgems.get_property_list(self.params["GridName2"]["grid"])
        if final_prop2 in lst2:
            flag = 0
            i = 1
            while flag == 0:
                new_prop_name2 = final_prop2 + "_" + str(i)
                if new_prop_name2 not in lst2:
                    flag = 1
                    final_prop2 = new_prop_name2
            i = i + 1
        print final_prop2
        sgems.set_property(self.params["GridName2"]["grid"], final_prop2, PP)

        return True
In this file, direction data is exported as vector to be visulized at Paraview (after Glyph filter)
The output file goes to SGeMS main folder as "points.vtu"
"""

import numpy as np 
import sgems
from pyevtk.hl import pointsToVTK


# Input properties (NEED TO INPUT grid name, direction data and ratio for coloring)
grid = "grid1"
direction_data = "05strike"
ratio_data = "05ratio"

# Initializing
prop = sgems.get_property(grid,direction_data)
ratio = sgems.get_property(grid,ratio_data)

propX = sgems.get_property(grid,"_X_")
propY = sgems.get_property(grid,"_Y_")
propZ = sgems.get_property(grid,"_Z_")
npoints = len(propX)

x = np.array(propX)
y = np.array(propY)
z = np.array(propZ)
vx = np.zeros(npoints)  
vy = np.zeros(npoints)  
vz = np.zeros(npoints)
rang = np.zeros(npoints)