# BoundsError: attempt to access 55-element Vector{Float64} at index \[3-element BitVector\] OR UndefVarError: \`vertex\_counter\` not defined

**URL:** <https://discourse.julialang.org/t/boundserror-attempt-to-access-55-element-vector-float64-at-index-3-element-bitvector-or-undefvarerror-vertex-counter-not-defined/121955>\
**Category:** New to Julia\
**Tags:** agents, graphs\
**Created:** [October 29, 2024, 5:26pm UTC](https://discourse.julialang.org/t/boundserror-attempt-to-access-55-element-vector-float64-at-index-3-element-bitvector-or-undefvarerror-vertex-counter-not-defined/121955 "2024-10-29T17:26:06Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![tfranks](https://avatars.discourse-cdn.com/v4/letter/t/898d66/32.png) [@tfranks](https://discourse.julialang.org/u/tfranks)\
**Post date:** [October 29, 2024, 5:26pm UTC](https://discourse.julialang.org/t/boundserror-attempt-to-access-55-element-vector-float64-at-index-3-element-bitvector-or-undefvarerror-vertex-counter-not-defined/121955/1 "2024-10-29T17:26:07Z")

</div>

Hello,

I’ve created bank and depositor agents and would now like to render as a graph with banks as the nodes and the depositors forming the edges that change at every time step. A snippet of the data frame is inserted below. For example, at time 0 depositor #1 withdraws from bank #405.

 ![image](https://global.discourse-cdn.com/julialang/original/3X/f/f/ffed683ddb3e88b745b92c9da687b776d4266ea3.png)

I want the network to look something like this.

 ![image](https://global.discourse-cdn.com/julialang/original/3X/d/7/d7fe6f17e7c7f145087c9730f0a19c6c73959937.png)

The problem is the bank “FOR loop.” If the “vertex\_counter” is inside the FOR loop, there’s a “BoundsError.” If the “vertex\_counter” is outside the FOR loop, there’s an “UnderVarError.” I’d appreciate your insights. Thank you.

‘’’

> df = CSV.read(“//Users/teresafranks/Documents/Dissertation/Charts/testDepositorBankData.csv”, DataFrame)
> 
> # Create a directed graph
> 
> g = SimpleDiGraph()
> 
> # Add vertices for banks and group them by social\_network
> 
> banks = unique(df.bank\_id)  
> social\_network\_groups = Dict{Int, Vector{Int}}()
> 
> # Create a mapping from bank IDs to graph vertices
> 
> vertex\_map = Dict{Int, Int}()  
> vertex\_counter = 1 # ??? vertex\_counter before loop or after loop? Neither works.
> 
> for bank in banks  
> #vertex\_counter = 1  
> vertex\_map[bank] = vertex\_counter  
> add\_vertex!(g)  
> social\_network = df[df.bank\_id .== bank, :social\_network][1]  
> if haskey(social\_network\_groups, social\_network)  
> push!(social\_network\_groups[social\_network], vertex\_counter)  
> else  
> social\_network\_groups[social\_network] = [vertex\_counter]  
> end  
> vertex\_counter += 1  
> end
> 
> # Function to update the network at each time step
> 
> function update\_network!(g, df, t)  
> # Clear existing edges  
> for e in edges(g)  
> rem\_edge!(g, edges(g))  
> end
> 
> ```
> # Add edges from depositors to banks based on the current time step
> for row in eachrow(df)
> if row.time <= t
> depositor_id = row.depositor_id
> bank_vertex = vertex_map[row.bank_id]
> add_edge!(g, depositor_id, bank_vertex)
> end
> end
> 
> ```
> 
> end
> 
> # Function to plot the network
> 
> function plot\_network(g, social\_network\_groups, group\_colors, t)  
> # Assign colors to vertices based on their social\_network group  
> vertex\_colors = fill(“black”, nv(g))  
> for (group, vertices) in social\_network\_groups  
> for vertex in vertices  
> vertex\_colors[vertex] = group\_colors[group]  
> end  
> end
> 
> ```
> # Plot the graph with vertex colors using Plots.jl and GraphRecipes.jl
> graphplot(g, names=1:nv(g), nodecolor=vertex_colors, method=:spring, title="Time Step: $t")
> 
> ```
> 
> end
> 
> # Define colors for different social\_network groups
> 
> group\_colors = Dict{Int, String}()  
> color\_palette = distinguishable\_colors(length(keys(social\_network\_groups)))
> 
> #i = 1  
> for group in keys(social\_network\_groups)  
> i = 1  
> group\_colors[group] = hex(color\_palette[I])  
> i += 1  
> end
> 
> # Simulate the network evolution
> 
> max\_time = maximum(df.time)  
> for t in 1:max\_time  
> update\_network!(g, df, t)  
> plot\_network(g, social\_network\_groups, group\_colors, t)  
> sleep(1) # Pause for a second to visualize the evolution  
> end  
> ‘’’

---

<div class="post-metadata">

**Author:** ![eldee](https://avatars.discourse-cdn.com/v4/letter/e/b5a626/32.png) [@eldee](https://discourse.julialang.org/u/eldee)\
**Post date:** [October 29, 2024, 7:58pm UTC](https://discourse.julialang.org/t/boundserror-attempt-to-access-55-element-vector-float64-at-index-3-element-bitvector-or-undefvarerror-vertex-counter-not-defined/121955/2 "2024-10-29T19:58:24Z")

</div>

Hi,

### Formatting

Could you edit your post to improve the readability? You seem to currently have written the code using `>` (e.g.

> # This is a comment
> 
> str = “Hello world”  
> println(str)

), while to get proper formatting you should use triple backticks (```, not apostrophes (‘’') or quotes (“”)) and no `>` (e.g.

```julia
# This is a comment
str = "Hello world"
println(str)

```

).

### Error message / stacktrace

Could you post the full error message and stacktrace? This would help pinpoint the location of the problem. Also, in the case of `vertex_counter` outside of the for loop, if would help to know which variable is undefined 🙂 .

### Data

It would also help if you could share the data for the `DataFrame` (if legally possible), or even better, generate (fake) data, for a minimal working example. That way others can also debug the code.

For the same reason please also mention the dependencies you are using (presumably `using CSV, DataFrames, Graphs, Plots, GraphRecipes`).

### Some notes

- If you define `vertex_counter` inside the loop as

- In fact, you do not need a variable `vertex_counter` at all, as this information is already contained in `g` and can be extracted using `nv(g)`. Alternatively, since you just increment `vertex_counter` by `1` at the end of every iteration, you could use `for (vertex_counter, bank) in enumerate(banks)`.

- (The line

- In

---

<div class="post-metadata">

**Author:** ![tfranks](https://avatars.discourse-cdn.com/v4/letter/t/898d66/32.png) [@tfranks](https://discourse.julialang.org/u/tfranks)\
**Post date:** [October 29, 2024, 9:46pm UTC](https://discourse.julialang.org/t/boundserror-attempt-to-access-55-element-vector-float64-at-index-3-element-bitvector-or-undefvarerror-vertex-counter-not-defined/121955/3 "2024-10-29T21:46:42Z")

</div>

Dear Eldee,

Thank you. I’ll go through your feedback with care.

I see the backtick now; it’s with the Tilda character.

Here’s the error message with the counter **outside** the bank FOR loop:

┌ Warning: Assignment to `vertex_counter` in soft scope is ambiguous because a global variable by the same name exists: `vertex_counter` will be treated as a new local. Disambiguate by using `local vertex_counter` to suppress this warning or `global vertex_counter` to assign to the existing global variable.  
└ @ ~/Documents/dissertation/Julia/Network.jl:39  
ERROR: UndefVarError: `vertex_counter` not defined  
Stacktrace:  
[1] top-level scope  
@ ~/Documents/dissertation/Julia/Network.jl:31

Since I restarted my laptop, I’m now getting a different error message with the counter **inside** the bank FOR loop:

Warning: Assignment to `vertex_counter` in soft scope is ambiguous because a global variable by the same name exists: `vertex_counter` will be treated as a new local. Disambiguate by using `local vertex_counter` to suppress this warning or `global vertex_counter` to assign to the existing global variable.  
└ @ ~/Documents/dissertation/Julia/Network.jl:30  
ERROR: Unknown color: 000000  
Stacktrace:  
[1] error(::String, ::String)  
@ Base ./error.jl:44  
[2] \_parse\_colorant(desc::String)  
@ Colors ~/.julia/packages/Colors/E2qak/src/parse.jl:151  
[3] parse(::Type{RGBA{Float64}}, desc::String)  
@ Colors ~/.julia/packages/Colors/E2qak/src/parse.jl:207  
[4] plot\_color  
@ ~/.julia/packages/PlotUtils/wo8RM/src/colors.jl:5 [inlined]  
[5] |\>  
@ ./operators.jl:917 [inlined]  
[6] get\_series\_color(c::String, sp::Plots.Subplot{Plots.GRBackend}, n::Int64, seriestype::Symbol)  
@ Plots ~/.julia/packages/Plots/kLeqV/src/args.jl:1982  
[7] \_update\_series\_attributes!(plotattributes::RecipesPipeline.DefaultsDict, plt::Plots.Plot{…}, sp::Plots.Subplot{…})  
@ Plots ~/.julia/packages/Plots/kLeqV/src/args.jl:2078  
[8] add\_series!(plt::Plots.Plot{Plots.GRBackend}, plotattributes::RecipesPipeline.DefaultsDict)  
@ Plots ~/.julia/packages/Plots/kLeqV/src/pipeline.jl:377  
[9] \_process\_seriesrecipe(plt::Any, plotattributes::Any)  
@ RecipesPipeline ~/.julia/packages/RecipesPipeline/BGM3l/src/series\_recipe.jl:46  
[10] \_process\_seriesrecipes!(plt::Any, kw\_list::Any)  
@ RecipesPipeline ~/.julia/packages/RecipesPipeline/BGM3l/src/series\_recipe.jl:27  
[11] recipe\_pipeline!(plt::Any, plotattributes::Any, args::Any)  
@ RecipesPipeline ~/.julia/packages/RecipesPipeline/BGM3l/src/RecipesPipeline.jl:99  
[12] \_plot!(plt::Plots.Plot, plotattributes::Any, args::Any)  
@ Plots ~/.julia/packages/Plots/kLeqV/src/plot.jl:223  
[13] #plot#188  
@ ~/.julia/packages/Plots/kLeqV/src/plot.jl:102 [inlined]  
[14] plot  
@ ~/.julia/packages/Plots/kLeqV/src/plot.jl:93 [inlined]  
[15] graphplot  
@ ~/.julia/packages/RecipesBase/BRe07/src/RecipesBase.jl:380 [inlined]  
[16] plot\_network(g::SimpleDiGraph{…}, social\_network\_groups::Dict{…}, group\_colors::Dict{…}, t::Int64)  
@ Main ~/Documents/dissertation/Julia/Network.jl:70  
[17] top-level scope  
@ ~/Documents/dissertation/Julia/Network.jl:88  
Some type information was truncated. Use `show(err)` to see complete types.

```julia
#File to create a network graph from the DepositorBankData.csv file
using Pkg
Pkg.activate(".")
Pkg.instantiate()

using DataFrames
using Graphs
using CSV
using GraphPlot
using Plots
using GraphRecipes
using Colors

# Load the data from the CSV file
df = CSV.read("//Users/teresafranks/Documents/Dissertation/Charts/DepositorBankData.csv", DataFrame)

# Create a directed graph
g = SimpleDiGraph()

# Add vertices for banks and group them by social_network
banks = unique(df.bank_id)
social_network_groups = Dict{Int, Vector{Int}}()

# Create a mapping from bank IDs to graph vertices
vertex_map = Dict{Int, Int}()
#vertex_counter = 1 # ???? vertex_counter before loop or after loop? Neither works.

for bank in banks
    vertex_counter = 1
    vertex_map[bank] = vertex_counter
    add_vertex!(g)
    social_network = df[df.bank_id .== bank, :social_network][1]
    if haskey(social_network_groups, social_network)
        push!(social_network_groups[social_network], vertex_counter)
    else
        social_network_groups[social_network] = [vertex_counter]
    end
    vertex_counter += 1
end

# Function to update the network at each time step
function update_network!(g, df, t)
    # Clear existing edges
    for e in edges(g)
        rem_edge!(g, edges(g))
    end

    # Add edges from depositors to banks based on the current time step
    for row in eachrow(df)
        if row.time <= t
            depositor_id = row.depositor_id
            bank_vertex = vertex_map[row.bank_id]
            add_edge!(g, depositor_id, bank_vertex)
        end
    end
end

# Function to plot the network
function plot_network(g, social_network_groups, group_colors, t)
    # Assign colors to vertices based on their social_network group
    vertex_colors = fill("black", nv(g))
    for (group, vertices) in social_network_groups
        for vertex in vertices
            vertex_colors[vertex] = group_colors[group]
        end
    end

    # Plot the graph with vertex colors using Plots.jl and GraphRecipes.jl
    graphplot(g, names=1:nv(g), nodecolor=vertex_colors, method=:spring, title="Time Step: $t")
end

# Define colors for different social_network groups
group_colors = Dict{Int, String}()
color_palette = distinguishable_colors(length(keys(social_network_groups)))

#i = 1
for group in keys(social_network_groups)
    i = 1
    group_colors[group] = hex(color_palette[i])
    i += 1
end

# Simulate the network evolution
max_time = maximum(df.time)
for t in 1:max_time
    update_network!(g, df, t)
    plot_network(g, social_network_groups, group_colors, t)
    sleep(1) # Pause for a second to visualize the evolution
end

```

Perhaps this message file size is too big, since I can’t upload the data frames. I’ll send in a separate message. Thanks again.

---

<div class="post-metadata">

**Author:** ![tfranks](https://avatars.discourse-cdn.com/v4/letter/t/898d66/32.png) [@tfranks](https://discourse.julialang.org/u/tfranks)\
**Post date:** [October 29, 2024, 10:09pm UTC](https://discourse.julialang.org/t/boundserror-attempt-to-access-55-element-vector-float64-at-index-3-element-bitvector-or-undefvarerror-vertex-counter-not-defined/121955/4 "2024-10-29T22:09:27Z")

</div>

For some reason, I’m not able to upload a CSV. Only allows JPEG? Please advise. Thank you.

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [October 30, 2024, 8:59am UTC](https://discourse.julialang.org/t/boundserror-attempt-to-access-55-element-vector-float64-at-index-3-element-bitvector-or-undefvarerror-vertex-counter-not-defined/121955/5 "2024-10-30T08:59:40Z")

</div>

Paste it in a GitHub gist or some other pastebin

---

<div class="post-metadata">

**Author:** ![tfranks](https://avatars.discourse-cdn.com/v4/letter/t/898d66/32.png) [@tfranks](https://discourse.julialang.org/u/tfranks)\
**Post date:** [October 30, 2024, 2:25pm UTC](https://discourse.julialang.org/t/boundserror-attempt-to-access-55-element-vector-float64-at-index-3-element-bitvector-or-undefvarerror-vertex-counter-not-defined/121955/6 "2024-10-30T14:25:24Z")

</div>

Thank you, jling!

---

<div class="post-metadata">

**Author:** ![eldee](https://avatars.discourse-cdn.com/v4/letter/e/b5a626/32.png) [@eldee](https://discourse.julialang.org/u/eldee)\
**Post date:** [October 30, 2024, 6:27pm UTC](https://discourse.julialang.org/t/boundserror-attempt-to-access-55-element-vector-float64-at-index-3-element-bitvector-or-undefvarerror-vertex-counter-not-defined/121955/7 "2024-10-30T18:27:34Z")

</div>

I see, you’re running your code as a script. In general you should then place (almost) all of the code inside functions (e.g. a `main` function which you call at the end of your script). This will help for performance, and also get rid of your scope issue when defining `vertex_counter` (and later `i`) outside of the for loop.

> **Example**
>
> When run as a script
> 
> ```julia
> x = 0
> for i = 1:5
> x += 1
> end
> println(x)
> 
> ```
> 
> indeed throws an exception
> 
> ```julia
> ┌ Warning: Assignment to `x` in soft scope is ambiguous because a global variable by the same name exists: `x` will be treated as a new local. Disambiguate by using `local x` to suppress this warning or `global x` to assign to the existing global variable.
> └ @ (...)\example.jl:3
> ERROR: LoadError: UndefVarError: `x` not defined
> Stacktrace:
> [1] top-level scope
> @ (...)\example.jl:3
> in expression starting at (...)\example.jl:2
> 
> ```
> 
> while
> 
> ```julia
> function main()
> x = 0
> for i = 1:5
> x += 1
> end
> println(x)
> end
> 
> main()
> 
> ```
> 
> runs fine:
> 
> ```julia
> 5
> 
> ```

If you then define your variables outside of the loop (which you should, keeping the first note in my previous post in mind), you will still run into the second error. The solution here is to simply not use `hex`.

> **Example**
>
> ```julia
> using Plots
> 
> function main()
> x = rand(10) |> sort
> y = rand(10)
> color_palette = distinguishable_colors(10)
> plot(x, y, color=hex.(color_palette))
> end
> 
> main()
> 
> ```
> 
> will throw
> 
> ```julia
> ERROR: Unknown color: 000000
> 
> ```
> 
> but
> 
> ```julia
> using Plots
> 
> function main()
> x = rand(10) |> sort
> y = rand(10)
> color_palette = distinguishable_colors(10)
> plot(x, y, color=color_palette)
> end
> 
> main()
> 
> ```
> 
> successfully displays.

---

<div class="post-metadata">

**Author:** ![tfranks](https://avatars.discourse-cdn.com/v4/letter/t/898d66/32.png) [@tfranks](https://discourse.julialang.org/u/tfranks)\
**Post date:** [October 30, 2024, 6:37pm UTC](https://discourse.julialang.org/t/boundserror-attempt-to-access-55-element-vector-float64-at-index-3-element-bitvector-or-undefvarerror-vertex-counter-not-defined/121955/8 "2024-10-30T18:37:07Z")

</div>

Super. That works.

Thank you!
