How to add a texture to the prefab in unity - c#

I have unity script which will instantiate objects during the runtime. I need to add a texture to my prefab. I went through some solutions and i couldnt find a proper solution. my code is
using UnityEngine;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class createWalls : MonoBehaviour {
bool creating;
public GameObject start;
public GameObject end;
int k=0;
int count = 0;
public TextAsset TextFile;
public GameObject wallPrehab;
GameObject wall;
public Collider coll;
public Camera c1;
public Camera c2;
public Manager mgr;
/*
*even we though it get as x,y values when modeling convert it's y value as z
*/
Vector3[] coordinatesX = null;
Vector3[] coordinatesY = null;
public Texture texture;
/*
* Use this for initialization
*/
void Start () {
readTextFileLines();
Vector3 start = new Vector3();
Vector3 end = new Vector3();
for (int i = 0; i < coordinatesX.Length; i++)
{
k = i + 1;
if (k != coordinatesX.Length)
{
if(coordinatesX[i].x == coordinatesX[k].x){
start = coordinatesX[i];
end = coordinatesX[k];
setStart(start);
setEnd(end);
adjust();
}
}
}
for(int j = 0; j < coordinatesY.Length; j++){
k = j + 1;
if (k != coordinatesY.Length)
{
if(coordinatesY[j].z == coordinatesY[k].z){
start = coordinatesY[j];
end = coordinatesY[k];
setStart(start);
setEnd(end);
adjust();
}
}
}
}
// Update is called once per frame
void Update () {
//getinput();
}
/*
* getting the mouse clicked position coordinate
*/
int number=0;
void setStart(Vector3 x){
creating = true;
start.transform.position = x;
wall = Instantiate (wallPrehab, start.transform.position, Quaternion.identity)as GameObject;
wall.GetComponent<WallScript>().mgr=mgr;
wall.gameObject.name = number.ToString ();
number++;
}
/*
* getting the mouse click over position coordinate
*/
void setEnd(Vector3 y){
end.transform.position = y;
}
/*
* invoking the wall building method
*/
void adjust(){
adjustWall ();
}
/*
* build the wall in between start point and the end point
*/
void adjustWall(){
start.transform.LookAt (end.transform.position);
end.transform.LookAt (start.transform.position);
float distance = Vector3.Distance (start.transform.position, end.transform.position);
wall.transform.position = start.transform.position + distance / 2 * start.transform.forward;
wall.transform.rotation = start.transform.rotation;
wall.transform.localScale = new Vector3 (wall.transform.localScale.x, wall.transform.localScale.y, distance);
}
/*
* Reading from the text file
*/
void readTextFileLines()
{
int count = 0;
string splits = TextFile.text.TrimStart ('[');
string[] split = TextFile.text.Split (')');
string split_1 = null;
string split_2 = null;
string split_3 = null;
int pos = 0;
int lengthOfString = 0;
int valX, valZ, valX1, valZ1 = 0;
/*
* Getting the count of the coordinates in the array
*/
foreach (string x in split) {
count++;
}
string[] stringArr = new string[count];
int[] xSortX = new int[count];
int[] xSortZ = new int[count];
int[] ySortX = new int[count];
int[] ySortZ = new int[count];
/*
* Splitting the coordinates as x,y and store in an array
*/
foreach (string coord in split) {
split_1 = coord;
split_1 = split_1.Trim ('[');
split_1 = split_1.Trim ('(');
split_1 = split_1.Trim (',');
split_1 = split_1.Trim (' ');
split_1 = split_1.Trim ('(');
split_1 = split_1.TrimEnd (']');
stringArr [pos] = split_1;
pos++;
}
//Debug.Log("Array Length " + stringArr.Length);
/*
* extracting simalar x coordinates
*/
//Debug.Log("");
//Debug.Log("-----------------extracting simalar x coordinates----------------");
//Debug.Log("");
int indexX = 0;
int loopRunX = 0;
for (int a = 0; a < stringArr.Length - 1; a = indexX) {
split_2 = stringArr [a];
lengthOfString = split_2.Length;
valX = int.Parse (split_2.Substring (0, split_2.IndexOf (',')));
valZ = int.Parse (split_2.Substring (split_2.IndexOf (' '), (lengthOfString - split_2.IndexOf (' '))));
for (int x1 = indexX; x1 < stringArr.Length - 1; x1++) {
split_3 = stringArr [x1];
lengthOfString = split_3.Length;
valX1 = int.Parse (split_3.Substring (0, split_3.IndexOf (',')));
valZ1 = int.Parse (split_3.Substring (split_3.IndexOf (' '), (lengthOfString - split_3.IndexOf (' '))));
//Check for the simillar x in the text file we provide
if (valX == valX1) {
xSortX [indexX] = valX1;
xSortZ [indexX] = valZ1;
//Debug.Log("X is " + valX + " and the coordinates which have simillar x ==> (" + valX1 + ", " + valZ1 + "). Index is " + x1);
//Debug.Log("xSortX["+indexX+"] is :"+xSortX[indexX]);
//Debug.Log("xSortZ["+indexX+"] is :"+xSortZ[indexX]);
indexX++;
} else {
break;
}
}
loopRunX++;
//indexX = indexX + countx;
//Debug.Log("Next Index to check onwards : " + indexX);
//Debug.Log("Looping Count : " + loopRunX);
//Debug.Log("");
}
coordinatesX = new Vector3[count];
/*
* Adding the x and z coorinates values to Vector3 array to build the object in coordinates x
*/
for (int x =0; x<count; x++) {
Vector3 createVArray = new Vector3 (xSortX [x], 0, xSortZ [x]);
coordinatesX [x] = createVArray;
//Debug.Log("Coordinates X :"+coordinatesX[x]);
}
/*
* extracting simalar x coordinates
*/
//Debug.Log("");
//Debug.Log("-----------------extracting simalar Y coordinates----------------");
//Debug.Log("");
int[] checker = new int[count];
bool eq = false;
int indexY = 0;
loopRunX = 0;
for (int a = 0; a < stringArr.Length - 1; a++) {
split_2 = stringArr [a];
lengthOfString = split_2.Length;
valX = int.Parse (split_2.Substring (0, split_2.IndexOf (',')));
valZ = int.Parse (split_2.Substring (split_2.IndexOf (' '), (lengthOfString - split_2.IndexOf (' '))));
foreach (int check in checker) {
if (check == valZ) {
eq = false;
break;
} else {
eq = true;
}
}
if (eq) {
checker [a] = valZ;
for (int x1 = a; x1 < stringArr.Length - 1; x1++) {
split_3 = stringArr [x1];
lengthOfString = split_3.Length;
valX1 = int.Parse (split_3.Substring (0, split_3.IndexOf (',')));
valZ1 = int.Parse (split_3.Substring (split_3.IndexOf (' '), (lengthOfString - split_3.IndexOf (' '))));
//Check for the simillar x in the text file we provide
if (valZ == valZ1) {
ySortX [indexY] = valX1;
ySortZ [indexY] = valZ1;
//Debug.Log("Y is " + valZ + " and the coordinates which have simillar z ==> (" + valX1 + ", " + valZ1 + "). Index is " + x1);
//Debug.Log("ySortX["+indexY+"] is :"+ySortX[indexY]);
//Debug.Log("ySortZ["+indexY+"] is :"+ySortZ[indexY]);
indexY++;
}
}
loopRunX++;
}
//Debug.Log("");
}
coordinatesY = new Vector3[count];
/*
* Adding the x and z coorinates values to Vector3 array to build the object in coordinates x
*/
for (int x =0; x<count; x++) {
Vector3 createVArray = new Vector3 (ySortX [x], 0, ySortZ [x]);
coordinatesY [x] = createVArray;
//Debug.Log("Coordinates Y :"+coordinatesY[x]);
}
}
I need to add this texture to my gameObject prefab

Related

Implementing Transvoxel algorithm, Gaps and Odd Mesh formations

I am trying to implement the Transvoxel algorithm for a game I am working on but I'm noticing some weird issues in the mesh generated:
Not sure why there are gaps and why the sphere has fins behind it.
For some reason, the mesh has gaps between chunks, and it has these strange fins extending out behind it. I haven't been able to figure out why this is happening but I have an inkling it may have to do with either the function that generates the density values for each Chunk (16x16x16 Block of cells):
private float SampleDensity(float3 _point)
{
var _worldPos = (_point / (m_WorldRadius - 1.0f) - 0.5f) * m_VolumeFieldSize;
var _halfS = m_VolumeFieldSize / 2;
var _maxD= Magnitude(new float3(_halfS, _halfS, _halfS));
var _fudge = 1f;
var _density = Magnitude(_worldPos) / (_maxD + _fudge) - 0.5f;
var _noise = CalculateNoise(_worldPos);
_density += _noise;
return _density;
}
public void Execute()
{
for (int _z = 0; _z < m_ChunkSize; _z++)
{
for (int _y = 0; _y < m_ChunkSize; _y++)
{
for (int _x = 0; _x < m_ChunkSize; _x++)
{
var _point = (new float3(_x, _y, _z) + (m_GPosition)); // Multiplying or dividing this value adjusts the final mesh's scale.
var _valueAtPoint = SampleDensity(_point);
m_Cells[_z * m_ChunkSize * m_ChunkSize + _y * m_ChunkSize + _x] = _valueAtPoint;
}
}
}
}
, or the mesh generating code itself:
for (int _z = 0; _z < _chunk.m_ChunkSize; _z++)
{
for (int _y = 0; _y < _chunk.m_ChunkSize; _y++)
{
for (int _x = 0; _x < _chunk.m_ChunkSize; _x++)
{
var _cubeConfiguration = 0;
for (int _i = 0; _i < 8; _i++)
{
_cornerPos = CornerIndex[_i];
_densityValues[_i] = _chunk.GetCell(_x + _cornerPos.x, _y + _cornerPos.y, _z + _cornerPos.z);
if (_densityValues[_i] < _chunk.m_World.m_ISOLevel) _cubeConfiguration |= (1 << _i);
}
var _caseCode = (byte) _cubeConfiguration;
if (_caseCode == 0) continue;
for (int _i = 0; _i < _cornerNormals.Length; _i++)
{
_cornerPos = CornerIndex[_i];
_cornerNormals[_i] = new Vector3(
_chunk.GetCell(_x + _cornerPos.x - 1, _y + _cornerPos.y, _z + _cornerPos.z) - _chunk.GetCell(_x + _cornerPos.x + 1, _y + _cornerPos.y, _z + _cornerPos.z),
_chunk.GetCell(_x + _cornerPos.x, _y + _cornerPos.y - 1, _z + _cornerPos.z) - _chunk.GetCell(_x + _cornerPos.x, _y + _cornerPos.y + 1, _z + _cornerPos.z),
_chunk.GetCell(_x + _cornerPos.x, _y + _cornerPos.y, _z + _cornerPos.z - 1) - _chunk.GetCell(_x + _cornerPos.x, _y + _cornerPos.y, _z + _cornerPos.z + 1)
);
}
var _cellClass = Transvoxel.regularCellClass[_caseCode];
Debug.Log($"Cell Class {_cellClass}");
var _vertexLocations = Transvoxel.RegularVertexData[_caseCode];
var _cellData = Transvoxel.RegularCellDatas[_cellClass];
var _vertexCount = _cellData.GetVertexCount();
var _triangleCount = _cellData.GetTriangleCount();
var _indexOffset = _cellData.vertexIndex;
for (int _i = 0; _i < _vertexCount; _i++)
{
ushort _edge = (ushort)(_vertexLocations[_i] & 255);
byte _v0 = (byte)((_edge >> 4) & 0x0F); //First Corner Index
byte _v1 = (byte)(_edge & 0x0F); //Second Corner Index
float _t = (_densityValues[_v1]) / (_densityValues[_v1] - _densityValues[_v0]);
Vector3 _p0 = new Vector3((_x + CornerIndex[_v0].x), (_y + CornerIndex[_v0].y), (_z + CornerIndex[_v0].z));
Vector3 _p1 = new Vector3((_x + CornerIndex[_v1].x), (_y + CornerIndex[_v1].y), (_z + CornerIndex[_v1].z));
var _position = (_p0 * _t) + ((1 - _t) * _p1);
var _n0 = CalculateNormal(_chunk, new Vector3Int((int) _p0.x, (int) _p0.y, (int) _p0.z));
var _n1 = CalculateNormal(_chunk, new Vector3Int((int) _p1.x, (int) _p1.y, (int) _p1.z));
var _normal = (_n0 + _t * (_n1 - _n0)).normalized;
m_Normals.Add(_normal);
m_Vertices.Add(_position);
m_UVs.Add(UvOffset[m_VCase]);
m_VCase = (byte)(m_VCase == 3 ? 0 : m_VCase + 1);
m_LocalVertexMapping[_i] = (ushort)(m_Vertices.Count - 1);
}
for (int _t = 0; _t < _triangleCount; _t++)
{
int _tm = _t * 3;
m_Triangles.Add(m_LocalVertexMapping[_indexOffset[_tm]]);
m_Triangles.Add(m_LocalVertexMapping[_indexOffset[_tm + 1]]);
m_Triangles.Add(m_LocalVertexMapping[_indexOffset[_tm + 2]]);
}
}
}
}
I am at a complete loss and would really appreciate some help as I've been racking my brains for close to 2 months on this, along with reading several papers on different MC Algorithms (Lengyel's included) for potential inspiration. Thank You.

How do I graph a-b=0?

Lets say a=x+y and b=2x-y and I want to plot a-b=0. I can manually rewrite this from (x+y)-(2x-y)=0 to y=.5x which makes it trivial to graph, but how do I rewrite it in code? Given x how do I calculate y if all I have is (x+y)-(2x-y)=0?
To be more specific, I am trying to graph the decision boundary of a neural network. I want to be able to change the layers and outputs at will, essentially changing the function I get as an output.
This is an example of an output I could get:
(x_1 w_2 + x_2 w_2 + b_1) w_7
+ (x_1 w_3 + x_2 w_4 + b_2) w_8
+ (x_1 w_5 + x_2 w_6 + b_3) w_9
+ b_4 (x_1 w_1 + x_2 w_2 + b_1) w_10
+ (x_1 w_3 + x_2 w_4 + b_2) w_11
+ (x_1 w_5 + x_2 w_6 + b_3) w_12
+ b_5
It's a 1 by 2 matrix and I know all values except x2 which is the y-axis. In order to draw the decision boundary I have to calculate a-b=0 where a and b both contain x and y. I can manually separate y to get y=... ,but that's not an option if the results in the output matrix change. How do I seperate/calculate the y?
I am using c# in Unity and passing the points on the graph into the LineRenderer.
Alright, I found the solution the same day of posting the question but had already been messing about for days. It turned out to be a math question after all.
Here's a link to the specific setup for the neural network using a linear activation: https://www.desmos.com/calculator/crmeebqnfb
I manually rewrote the matrix multiplication for this specific setup into a function and was looking for a way to do that for any size and number of invisible layers.
The solution I found is to separate the input matrix into x1 and x2 and separately do the matrix multiplication for them. The x1 value gets the biases added but the x2 doesn't and the first weight matrix has to be split in 2 so x1 can get multiplied with the first row and x2 with the second row.
If you then do the matrix multiplication from there you'll get two 2 matrices like this:
[firstx1answer secondx1answer] [firstx2answer secondx2answer]
And then you can put them into this function:
Edit for better clarification:
Maybe a bit confusing but here's my code. CreateDecisionBoundaryPoints is where this is implemented:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.IO;
using System;
[ExecuteAlways]
public class Controller : MonoBehaviour
{
public Transform LineRenderer;
public GameObject textPrefab;
public GameObject pointPrefab;
public Transform weightsUI;
public Transform biasesUI;
[Range(.001f, .1f)] public float delta;
public int numberOfHiddenLayers;
public bool debugWeightMatrices;
public bool debugBiasMatrices;
[HideInInspector] public string[] dataValues;
private void Start()
{
if (Application.isPlaying)
{
//read file
int numberOfLines;
dataValues = ReadData("D:\\Documents\\Unity Projects\\Learning Machine Learning\\Assets\\Data.csv", out numberOfLines);
int numOfOutputNeurons = CreatePointsUI(numberOfLines, dataValues);
//create layerSizes for example [2,3,2]
int[] layerSizes = new int[numberOfHiddenLayers + 2];
layerSizes[0] = (dataValues.Length / numberOfLines) - 1;
layerSizes[numberOfHiddenLayers + 1] = numOfOutputNeurons;
for (int i = 0; i < numberOfHiddenLayers; i++)
{
layerSizes[i+1] = Mathf.Max((dataValues.Length / numberOfLines) - 1, numOfOutputNeurons) + 1;
}
//create the actual matrices
List<float[,]> weights = new List<float[,]>();
List<float[]> biases = new List<float[]>();
MakeTheMatrices(layerSizes, out weights, out biases);
//fill weights with random values
RandomlyFillMatrices(weights);
//print matrices to make sure they're the right size and filled randomly
if (debugWeightMatrices)
Debug.Log(PrintMatrices(weights, "Weight Matrices"));
if (debugBiasMatrices)
Debug.Log(PrintMatrices(biases, "Bias Matrices"));
LineRenderer.GetComponent<DrawDecisionBoundary>().DrawLine(CreateDecisionBoundaryPoints(weights, biases, delta));
}
}
public struct OutputNeuronsAndColours
{
public string value;
public Color color;
public OutputNeuronsAndColours(string value, Color color)
{
this.value = value;
this.color = color;
}
}
public void DoTheWeightsStufUI(int weights)
{
int cwn = 0;
List<Transform> ws = new List<Transform>();
foreach (Transform child in weightsUI)
{
cwn++;
ws.Add(child);
}
int wta = weights - cwn;
for (int i = wta; i < 0; i++)
{
cwn--;
DestroyImmediate(ws[cwn].gameObject);
ws.RemoveAt(cwn);
}
for (int i = wta; i > 0; i--)
{
cwn++;
GameObject weight = Instantiate(textPrefab, weightsUI);
weight.GetComponentInChildren<TMP_Text>().SetText("W" + cwn.ToString());
}
}
public void DoTheBiasesStufUI(int biases)
{
int cbn = 0;
List<Transform> bs = new List<Transform>();
foreach (Transform child in biasesUI)
{
cbn++;
bs.Add(child);
}
int bta = biases - cbn;
for (int i = bta; i < 0; i++)
{
cbn--;
DestroyImmediate(bs[cbn].gameObject);
bs.RemoveAt(cbn);
}
for (int i = bta; i > 0; i--)
{
cbn++;
GameObject bias = Instantiate(textPrefab, biasesUI);
bias.GetComponentInChildren<TMP_Text>().SetText("B" + cbn.ToString());
}
}
string[] ReadData(string path, out int numberOfLines)
{
List<string> data_values = new List<string>();
StreamReader strReader = new StreamReader(path);
bool endOfFile = false;
int numOfLines = 0;
while (!endOfFile)
{
string data_string = strReader.ReadLine();
if (data_string == null)
{
endOfFile = true;
break;
}
else
numOfLines += 1;
data_values.AddRange(data_string.Split(','));
}
numberOfLines = numOfLines;
return data_values.ToArray();
}
int CreatePointsUI(int numberOfLines, string[] dataValues)
{
string[] possibleOutputs = new string[numberOfLines];
for (int i = 0; i < numberOfLines; i++)
{
possibleOutputs[i] = dataValues[(i * (dataValues.Length / numberOfLines)) + ((dataValues.Length / numberOfLines) - 1)];
}
List<OutputNeuronsAndColours> outputNeurons = new List<OutputNeuronsAndColours>(possibleOutputs.Length);
for (int i = 0; i < possibleOutputs.Length; i++)
{
bool contains = false;
for (int x = 0; x < outputNeurons.Count; x++)
{
if (possibleOutputs[i] == outputNeurons[x].value)
contains = true;
}
if (!contains)
outputNeurons.Add(new OutputNeuronsAndColours(possibleOutputs[i], new Color(UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f))));
}
for (int i = 0; i < numberOfLines; i++)
{
GameObject point = Instantiate(pointPrefab);
point.transform.position = new Vector2(float.Parse(dataValues[i * (dataValues.Length / numberOfLines)]), float.Parse(dataValues[(i * (dataValues.Length / numberOfLines)) + 1]));
foreach (OutputNeuronsAndColours value in outputNeurons)
{
if (value.value == dataValues[(i * (dataValues.Length / numberOfLines)) + ((dataValues.Length / numberOfLines) - 1)])
point.GetComponent<SpriteRenderer>().color = value.color;
}
}
return outputNeurons.Count;
}
public static void MakeTheMatrices(int[] layerSizes, out List<float[,]> weights, out List<float[]> biases)
{
List<float[,]> tempWeights = new List<float[,]>();
List<float[]> tempBiases = new List<float[]>();
for (int i = 0; i < layerSizes.Length - 1; i++)
{
tempWeights.Add(new float[layerSizes[i], layerSizes[i + 1]]);
}
for (int i = 1; i < layerSizes.Length; i++)
{
List<float> temp = new List<float>();
for (int x = 0; x < layerSizes[i]; x++)
temp.Add(0);
tempBiases.Add(temp.ToArray());
}
weights = tempWeights;
biases = tempBiases;
}
public static void RandomlyFillMatrices(List<float[,]> matrices)
{
foreach (float[,] matrix in matrices)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int x = 0; x < matrix.GetLength(1); x++)
{
matrix[i, x] = UnityEngine.Random.Range(-3f, 3f);
}
}
}
}
public static string PrintMatrices(List<float[,]> matrices, string name = "Count")
{
string returnString = matrices.Count + " " + name;
foreach (float[,] matrix in matrices)
{
returnString += " (" + matrix.GetLength(0) + ", " + matrix.GetLength(1) + ")";
for (int i = 0; i < matrix.GetLength(0); i++)
{
string log = "";
if (i == 0)
log += "[";
else
log += " ";
for (int x = 0; x < matrix.GetLength(1); x++)
{
log += matrix[i, x];
if(x != matrix.GetLength(1) - 1)
log += " ";
}
if (i == matrix.GetLength(0) - 1)
log += "]";
Debug.Log(log);
}
}
return returnString;
}
public static string PrintMatrices(List<float[]> matrices, string name = "Count")
{
string returnString = matrices.Count + " " + name;
foreach (float[] matrix in matrices)
{
returnString += " (" + matrix.Length + ")";
string log = "[";
for (int i = 0; i < matrix.Length; i++)
{
log += matrix[i];
if (i != matrix.Length - 1)
log += " ";
}
log += "]";
Debug.Log(log);
}
return returnString;
}
private Vector3[] CreateDecisionBoundaryPoints(List<float[,]> weights, List<float[]> biases, float delta)
{
//check whether there are exactly 2 input neurons
if (weights[0].GetLength(0) != 2)
Debug.LogError("Not exactly 2 input neurons!");
//check whether there are exactly 2 output neurons
if (biases[biases.Count - 1].Length != 2)
Debug.LogError("Not exactly 2 output neurons!");
//create the values for the first layer
float[] weightsForFirstLayerX = new float[weights[0].GetLength(1)];
for (int i = 0; i < weights[0].GetLength(1); i++)
{
weightsForFirstLayerX[i] = weights[0][0, i];
}
float[] denominatorValuesFirstLayer = new float[weights[0].GetLength(1)];
for (int i = 0; i < weights[0].GetLength(1); i++)
{
denominatorValuesFirstLayer[i] = weights[0][1, i];
}
List<Vector3> pointsForGraph = new List<Vector3>();
//Calculate the y value(s) for each x with interval delta
for (float x = -.04f; x <= 1 + delta; x += delta)
{
float[] numeratorValuesFirstLayer = new float[weightsForFirstLayerX.Length];
for (int i = 0; i < weightsForFirstLayerX.Length; i++)
numeratorValuesFirstLayer[i] = x * weightsForFirstLayerX[i] + biases[0][i];
//get the row matrices for the decision boundary function
float[] numeratorResults = PassValuesThroughMatrices(numeratorValuesFirstLayer, weights, biases, true);
float[] denominatorResults = PassValuesThroughMatrices(denominatorValuesFirstLayer, weights, biases, false);
float y = (numeratorResults[1] - numeratorResults[0]) / (denominatorResults[0] - denominatorResults[1]);
pointsForGraph.Add(new Vector3(x, y, -1));
}
return pointsForGraph.ToArray();
}
private float[] PassValuesThroughMatrices(float[] values, List<float[,]> weights, List<float[]> biases, bool isNumerator)
{
float[] previousLayer = values;
//loop passing the previous layer values through the current layer: values = values * weights + biases
for (int i = 1; i < weights.Count; i++)
{
float[] temp = new float[weights[i].GetLength(1)];
//loop through the colums in the weight matrix
for (int v = 0; v < weights[i].GetLength(1); v++)
{
float value = 0;
//loop through the rows in the weight matrix
for (int b = 0; b < weights[i].GetLength(0); b++)
value += previousLayer[b] * weights[i][b, v];
if (isNumerator)
value += biases[i][v];
temp[v] = value;
}
previousLayer = temp;
}
//return the last itteration of values
return previousLayer;
}
}

ArgumentNullException: Argument cannot be null c#(Unity)

Here is my code :
string playerwinnopairboth = "P ";
IEnumerator WinLog_big_road()
{
string[] historyvalue = { };
historyvalue = tzPlayInfo.Instance.HistoryValue;
/*-------------------------------*/
NetworkManager.instance.WebSocketServer.OnCallBack_SC_WEBSOCKET_BcGametableHistory += CallBack_CS_WEBSOCKET_BcGametableHistory;
/*-------------------------------*/
DeleteChildrens(pos_big_road);
yield return new WaitForEndOfFrame();
for (int i = 0; i < rh.Const._HISTORY_COUNT_CARD_ * rh.Const._HISTORY_DECK_; i++)
{
int x = i % rh.Const._HISTORY_COUNT_CARD_;
int y = i / rh.Const._HISTORY_COUNT_CARD_;
float xl = 2.0f;
float yl = -5.0f;
GameObject o = Instantiate(prefab_big_road) as GameObject;
o.transform.SetParent(pos_big_road);
o.transform.localScale = Vector3.one;
o.transform.localPosition = new Vector3(x * xl, y * yl, 0f);
if (historyvalue.Contains(playerwinnopairboth))
{
//o.GetComponent<UISprite>().spriteName = "layout_player_bigline-01";
//NGUITools.SetActive(o, true);
Debug.Log("PLAYER WIN, NO PAIR , NO PAIR");
}
}
private void CallBack_CS_WEBSOCKET_BcGametableHistory(bool success, Int32 gametable_no, Int32 year, Int32 month, Int32 day, Int32 shoe_no, bc_gametable_history_list list)
{
string s1 = "";
for (int i = 0; i < tzPlayInfo.Instance.bc_gametable_history_list.Count; i++)
{
s1 += tzPlayInfo.Instance.bc_gametable_history_list[i].r;
s1 += ",";
}
tzPlayInfo.Instance.HistoryValue = s1.ToString().Split(',');
}
my tzPlayInfo values is like this:
private string[] historyvalue;
public string[] HistoryValue
{
get { return historyvalue; }
set { historyvalue = value; }
}
The Error is pointing me out here
if (historyvalue.Contains(playerwinnopairboth))
{
//o.GetComponent<UISprite>().spriteName = "layout_player_bigline-01";
//NGUITools.SetActive(o, true);
Debug.Log("PLAYER WIN, NO PAIR , NO PAIR");
}
I don't know why it's giving me a null value . Could someone point out what i am doing wrong here. Thank you in advance for those who will help me...

Cosine similarity calculation issue

I am having issues in calculation of cosine similarity between 2 strings.
I calculate the binary vector format of each string using a function. It gives out binary vectors which are in the form of, say, (1,1,1,1,1,0,0,0,0).
public static Tuple<int[],int[]> sentence_to_vector(String[] word_array1, String[] word_array2)
{
String[] unique_word_array1 = word_array1.Distinct().ToArray();
String[] unique_word_array2 = word_array2.Distinct().ToArray();
String[] list_all_words = unique_word_array1.Concat(unique_word_array2).ToArray();
String[] list_all_words_unique = list_all_words.Distinct().ToArray();
int count_all_unique_words = list_all_words_unique.Length;
int[] sentence1_vector = new int[count_all_unique_words];
int[] sentence2_vector = new int[count_all_unique_words];
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(unique_word_array1, list_all_words_unique[i]) >= 0)
{
sentence1_vector[i] = 1;
}
else
{
sentence1_vector[i] = 0;
}
}
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(word_array2, list_all_words_unique[i]) >= 0)
{
sentence2_vector[i] = 1;
}
else
{
sentence2_vector[i] = 0;
}
}
return Tuple.Create(sentence1_vector, sentence2_vector);;
}
After I calculate the vector representation, I go for cosine similarity calculation.
The code is attached herewith:
public static float get_cosine_similarity(int[] sentence1_vector, int[] sentence2_vector)
{
int vector_length = sentence1_vector.Length;
int i = 0;
float numerator = 0, denominator = 0;
int temp1 = 0, temp2 = 0;
double square_root1 = 0, square_root2 = 0;
for (i = 0; i < vector_length; i++)
{
numerator += sentence1_vector[i] * sentence2_vector[i];
temp1 += sentence1_vector[i] * sentence1_vector[i];
temp2 += sentence2_vector[i] * sentence2_vector[i];
}
//TextWriter tw = new StreamWriter("E://testpdf/date2.txt");
square_root1 = Math.Sqrt(temp1);
square_root2 = Math.Sqrt(temp2);
denominator = (float)(square_root1 * square_root2);
if (denominator != 0){
return (float)(numerator / denominator);
//return (float)(numerator);
}
else{
return 0;
}
}
I checked out a site where in I can specify 2 strings and find the cosine similarity between them. The site is attached herewith:
http://cs.uef.fi/~zhao/Link/Similarity_strings.html
function implementationCosin(){
var string1 = document.DPAform.str1.value;
var s1 = stringBlankCheck(string1);
var string2 = document.DPAform.str2.value;
var s2 = stringBlankCheck(string2);
if (s1.length < 1) {
alert("Please input the string1.");
return;
}
if (s2.length < 1) {
alert("Please input the string2.");
return;
}
document.DPAform.displayArea2.value = "";
var sDT = new Date();
// var begin = new Date().getTime();
var cosin_similarity_value = consinSimilarity(s1, s2);
document.DPAform.displayArea2.value += 'Cosin_Similarity(' + s1 + ',' + s2 + ')=' + cosin_similarity_value + '%\n';
var eDT = new Date();
var timediff = sDT.dateDiff("ms", eDT);
// var timediff = (new Date().getTime() - begin);
document.DPAform.displayArea2.value += "The total escaped time is: " + timediff + " (ms).\n";
}
Even if 2 sentences are 0% similar, my codes says that there is some amount of similarity between them.

Giving an error saying local variable is not assigned

This is a simple code I have written to solve a mathematical problem.
namespace StoreCredit
{
class Program
{
private static int No1;
static void Main(string[] args)
{
string[] text = System.IO.File.ReadAllLines(#"input.txt");
int nocases = int.Parse(text[0]);
int J = 1;
int No1=0;
int No2=0;
for (int x = 1; x <= nocases;x++ )
{
int Amount = int.Parse(text[J]);
int NoItem = int.Parse(text[J+1]);
char[] delimiterChars = { ' ' };
string[] Values = text[J+2].Split(delimiterChars);
int z = 0;
bool found = false;
while ((z < NoItem) && !found)
{
int Item = int.Parse(Values[z]);
int Remaining = Amount - Item;
int y = 0; bool found2 = false;
while ((y < NoItem) && !found2)
{
if (Remaining == int.Parse(Values[y])&&!(y==z))
{
Console.WriteLine("Found a match");
found = true;
found2 = true;
Console.WriteLine("Value 1 = {0} and Value 2={1}",(z+1),(y+1));
}
y++;
}
z++;
}
string lines = "Case #" + x + ": ", z, y;
StreamWriter file2 = new StreamWriter(#"output.txt", true);
file2.WriteLine(lines);
file2.Close();
J = J + 3;
}
}
}
}
I wanted to write the out put of this program to a text file. But I get an error saying z,y cannot be declared in this scope because it would give an different meanings to z,y. Can you please explain me the reason for this.
Thank you
This line near the end attempts to re-declare z and y, since you've separated them by commas:
string lines = "Case #" + x + ": ", z, y;
Did you intend to concatenate them instead? Such as:
string lines = "Case #" + x + ": " + z + y; // notice the + instead of comma

Categories

Resources