Convert IGH_Goo to integer

How to convert Grasshopper.Kernel.Types.IGH_Goo to integer?

I have a class which inputs a DataTree (of ints) from Grasshopper. Then it need to take its values from different branches and add to List.

int yourInt = new int();
yourGoo.CastTo(out yourInt);

and how to take a specific item from a specific Grasshopper.Kernel.Types.IGH_Goo datatree?

Can you be more specific? Are you within a a compiled component? A c# script component?

Also the DataTree has no type requirement, so for DataTree object is not constrained to be of type IGH_Goo.

I work in visual studio to write a compiled component to GH

Above problem is solved, now I need to do it other way around - to add integer to data tree of IGH_Goo…

Not sure I understand.

DataTree<int> tree = new DataTree<int>();
int i = 17;
GH_Path path = new GH_Path(1, 3);
tree.Add(i, path);

Not sure what the point is in using a GH_Integer type when working with a DataTree, the whole point of this class is that you can use native types.

Within a compiled component the recommendation though is to use GH_Structure<GH_Integer>. In that case the code would be something like this I think:

GH_Structure<GH_Integer> tree = new GH_Structure<GH_Integer>();
int i = 17;
GH_Path path = new GH_Path(1, 3);
tree.Append(new GH_Integer(i), path);

Thanks, i switched all trees to GH_Integer, and it all compiles perfectly, but when i run it in rihno…

Without code snippets I don’t know how to help. My code to use a tree of integers within a compiled component looks like that:

    protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
    {
        // pManager[0]: Integer Tree
        pManager.AddIntegerParameter("Input0",
            "Input0",
            "A datatree filled with integer values",
            GH_ParamAccess.tree);
    }


    protected override void SolveInstance(IGH_DataAccess DA)
    {
        if (!DA.GetDataTree(0, out GH_Structure<GH_Integer> tree))
        {
            this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Failed to retrieve data from input 0");
            return;
        }
    }

public class Comp_KMeans : GH_Component
{
///


/// Initializes a new instance of the Comp_KMeans class.
///

public Comp_KMeans()
: base(“KMeans”, “KMeans”,
“KMeans”,
“Wtyczka_Dynarek”, “Utils”)
{
}

    /// <summary>
    /// Registers all the input parameters for this component.
    /// </summary>
    protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
    {
        //pManager.AddBooleanParameter("Flock", "Flock", "Flock", GH_ParamAccess.item);
        
        pManager.AddIntegerParameter("Data Tree", "Data Tree", "Input data tree of branches equal to desired dimensions",GH_ParamAccess.tree);
        pManager.AddIntegerParameter("Samples", "Samples", "Samples", GH_ParamAccess.item);
        pManager.AddIntegerParameter("Dimensions", "Dimensions", "Dimensions", GH_ParamAccess.item);
        pManager.AddIntegerParameter("Iterations", "Iterations", "Iterations", GH_ParamAccess.item);
    }

    /// <summary>
    /// Registers all the output parameters for this component.
    /// </summary>
    protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
    {
        pManager.AddIntegerParameter("Count", "Count", "Count", GH_ParamAccess.item);
        pManager.AddIntegerParameter("Values", "Values", "Values", GH_ParamAccess.tree);
        pManager.AddIntegerParameter("Samples", "Samples", "Samples", GH_ParamAccess.tree);
        pManager.AddIntegerParameter("IDs", "IDs", "IDs", GH_ParamAccess.tree);
    }

    /// <summary>
    /// This is the method that actually does the work.
    /// </summary>
    /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
    protected override void SolveInstance(IGH_DataAccess DA)
    {

        GH_Structure<GH_Integer> kmValues = new GH_Structure<GH_Integer>();
        GH_Structure<GH_Integer> kmSamples = new GH_Structure<GH_Integer>();
        GH_Structure<GH_Integer> kmIds = new GH_Structure<GH_Integer>();

        GH_Structure<GH_Integer> iValues = new GH_Structure<GH_Integer>();
       // Grasshopper.DataTree<int> iValues = new Grasshopper.DataTree<int>;
        int iSamples = 0;
        int iDimensions = 0;
        int iIterations = 0;



        // DA.GetDataTree(0, out iValues);
        //
        if (!DA.GetDataTree(0, out  iValues))
        {
            this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Failed to retrieve data from input 0");
            return;
        }

        DA.GetData(1, ref iSamples);
        DA.GetData(2, ref iDimensions);
        DA.GetData(3, ref iIterations);

        KMeans km = new KMeans(iDimensions, iValues, iSamples);
        km.AssignSampleLists();

        for (int i = 0; i < iIterations; i++)
        {
            km.ReasignSamples();
            km.AssignSampleLists();
           
        }


        for (int i = 0; i < iSamples; i++)
        {
            KAgent sampleOne = km.listOfsampleLists[i].sample;
            for (int j = 0; j < iDimensions; j++)
            {
                GH_Path path = new GH_Path(i, j);
                // kmValues.Add(km.listOfsampleLists[i].values[j], path);
                // kmSamples.Add(sampleOne.valuesN[j], path);
                // int myInt = new int();
                GH_Integer myInt = new GH_Integer(sampleOne.valuesN[j]);
                //sampleOne.valuesN[j]

                kmSamples.Append(myInt, path);

            }
        }


        for (int i = 0; i < iValues.get_Branch(0).Count; i++)
        {
            KAgent agentOne = km.valueAgents[i];
            for (int j = 0; j < iDimensions; j++)
            {
                GH_Path path = new GH_Path(i, j);
                // kmValues.Add(km.listOfsampleLists[i].values[j], path);
                // kmValues.Add(agentOne.valuesN[j], path);

            }
        }


        for (int i = 0; i < km.listOfsampleLists.Count; i++)
        {

            for (int j = 0; j < km.listOfsampleLists[i].agents.Count; j++)
            {
                KAgent agentOne = km.listOfsampleLists[i].agents[j];
                for (int z = 0; z < iDimensions; z++)
                {
                    GH_Path path = new GH_Path(i, j, z);
                    GH_Integer myInt = new GH_Integer(agentOne.valuesN[z]);
               
                    kmValues.Append(myInt, path);
                }

            }
        }


        for (int i = 0; i < km.listOfsampleLists.Count; i++)
        {

            for (int j = 0; j < km.listOfsampleLists[i].agents.Count; j++)
            {
                KAgent agentOne = km.listOfsampleLists[i].agents[j];

                GH_Path path = new GH_Path(i);
                GH_Integer myInt = new GH_Integer(agentOne.id);

                kmIds.Append(myInt, path);


            }
        }


        


        DA.SetData(0, km.valueAgents.Count);
        DA.SetDataTree(3, kmIds);
        DA.SetDataTree(2, kmSamples);
        DA.SetDataTree(1, kmValues);



    }

Works fine for me. Maybe has something to do with what you plug into the first input parameter? Or try to recompile, make sure the new .gha is loaded, and maybe create a new component on the canvas.

If that still doesn’t work, hook your vs up properly, set a breakpoint and check what’s happing around the DA.GetDataTree().

On a sidenote, you can access the branch i of a GH_Structure by using the indexer (tree.Branches[0]), the get_Branch is an internal helper method as fas as I know.

uh. still no.

have a look at the class that uses my tree.

class KMeans
{
public List valueAgents = new List();
public List listOfsampleLists = new List();
int samplesCount;
int dimensions;

    public KMeans(int dim,
        GH_Structure<IGH_Goo> valuesTree, 
        int isamplesCount)
    {
        //DataTree<int> valuesTree

        dimensions = dim;
        samplesCount = isamplesCount;
        //boolTree.Branch(1,2)[5] = true;

//MAYBE THERE IS SOME ERROR HERE?
//tłumaczy drzewo danych o N gałęziach na listę Agentów z N parametrami
for (int i = 0; i < valuesTree.Branches[0].Count; i++)
{
// KAgent newAgent = new KAgent(new List());
List agentValues = new List();

            for (int j = 0; j < dimensions; j++)
            {
                //newAgent.valuesN[j] = valuesTree.Branch(j)[i];
                // valueAgents.Add(newAgent);

                //int yourInt = new int();
                // yourGoo.CastTo(out yourInt);
                int yourInt = new int();
               GH_Path path = new GH_Path(j);
                valuesTree.get_DataItem(path, i).CastTo(out yourInt);
                agentValues.Add(yourInt);
            }
            valueAgents.Add(new KAgent(agentValues, i));

        }

        //randomowe Sample

        Random r = new Random();
        for (int i = 0; i < samplesCount; i++)
        {
            List<KAgent> valuess = new List<KAgent>();
            int index = r.Next(valueAgents.Count);
            KAgent val = valueAgents[index];


            listOfsampleLists.Add(new SampleList(valuess, val));



        }
    }









    public void AssignSampleLists()
    {

        for (int i = 0; i < samplesCount; i++)
        {
            listOfsampleLists[i].agents.Clear();

        }

        for (int i = 0; i < valueAgents.Count; i++)
        {
            List<int> distancesPerSample = new List<int>();
            List<SampleDist> sampleWithDistances = new List<SampleDist>();

            for (int j = 0; j < samplesCount; j++)
            {
                KAgent sampleOne = listOfsampleLists[j].sample;
                List<int> distances = new List<int>();

                for (int z = 0; z < dimensions; z++)
                {
                    int dist = Math.Abs(sampleOne.valuesN[z] - valueAgents[i].valuesN[z]);
                    distances.Add(dist * dist);
                }

                int distPerSample = Convert.ToInt32(Math.Sqrt(distances.Sum()));
                distancesPerSample.Add(distPerSample);
                sampleWithDistances.Add(new SampleDist(distPerSample, sampleOne));
            }
            // List <SampleList> orderList = listOfsampleLists;
            //List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();
            //  List<SampleList> SortedList = objListOrder.OrderBy(o => o.OrderDate).ToList();
            List<SampleDist> SortedList = sampleWithDistances.OrderBy(o => o.dist).ToList();


            for (int y = 0; y < listOfsampleLists.Count(); y++)
            {
                if (listOfsampleLists[y].sample.Equals(SortedList[0].sample))
                {
                    listOfsampleLists[y].agents.Add(valueAgents[i]);
                }
            }


        }
    }




    public void ReasignSamples()
    {

        for (int j = 0; j < listOfsampleLists.Count; j++)

        {
            int avv;
            List<int> sampleValues = new List<int>();

            for (int i = 0; i < dimensions; i++)
            {
                List<int> dimNValues = new List<int>();

                for (int z = 0; z < listOfsampleLists[j].agents.Count; z++)
                {

                    int val = listOfsampleLists[j].agents[z].valuesN[i];
                    dimNValues.Add(val);

                }

                double av = dimNValues.Average();
                avv = Convert.ToInt32(av);
                sampleValues.Add(avv);
            }

            listOfsampleLists[j].sample = new KAgent(sampleValues, 0);

        }

    }

}

List agentValues = new List();

I’m surprised this compiles… Where is your list type?

valuesTree.get_DataItem(path, i).CastTo(out yourInt);

You get a KeyNotFoundException, I assume because the path is invalid or doesn’t exist? As far as I know GH_Structure is basically a dictionary with a GH_Path as key and a List<IGH_Goo> as value.

And the grasshopper breakpoint, no idea, it’s not related to the code you provided in your last post? At least I don’t see any GetDataTree() but that’s there the Error is thrown?

    GH_Structure<IGH_Goo> valuesTree, 

I’m pretty sure that that is also going to cause you trouble, you should specify a type for your structure (which derives from IGH_Goo)

Also you’re running a huge amount of code within the constructor of your class…

ok i got. the problem was so stupid that i am almost embarassed… tree that i inputed to component had tree branches with indexes like {0,1}{0,2} etc. and in the code i asked for {j}…“simplify tree” in gh script was enough to solve the problem :smiley: