main.jl 20 KB
Newer Older
1
2
using DataFrames
using CSV
3
using JSON
4
using LightGraphs
5
using NearestNeighbors
6
using Statistics
7
using BenchmarkTools
8
using Plots
9
using LinearAlgebra
10

11

12
13
14
15
16
17
18
struct material
    α::Number
    E::Number
    σ̄::AbstractArray{Number, 2} # Yield stress \sigma\bar
end


Jayant Khatkar's avatar
Jayant Khatkar committed
19
mutable struct contour
20
21
22
23
24
    pos
    time
end


25
struct contourdata
26
27
28
    contours::Vector{contour}
    G::SimpleDiGraph
    layers::Vector
29
    travel_dists::Dict
30
    layer_height::Number
31
32
33
end


34
35
36
37
struct voxmap
    seglen::Vector{Float64}
    segoffset::Vector{Float64}
    segcontours::Vector{Int}
38
    c::Number
39
40
41
42
43
44
45
46
47
48
49
end


struct voxdata
    voxels::DataFrame
    maps::Vector{voxmap}
    below::Vector{Int}
    width::Number
end


50
51
52
53
54
55
56
57
58
59
60
61
62
63
function vecvec_to_matrix(vecvec)
    # convert vector of vectors int a matrix
    dim1 = length(vecvec)
    dim2 = length(vecvec[1])
    my_array = zeros(Float32, dim1, dim2)
    for i in 1:dim1
        for j in 1:dim2
            my_array[i,j] = vecvec[i][j]
        end
    end
    return my_array
end


64
function contour(d::Dict)
65
    return contour(vecvec_to_matrix(d["pos"]), d["time"])
66
end
67

68

69
function contourdata(cons::Vector{contour}, max_layers::Int, min_dist::Number)
70
    G = LightGraphs.SimpleDiGraph(0)
71

72
    # separate contours into layers
73
    layer_heights = sort(collect(Set([c.pos[end,3] for c in cons])))
74
75
76
77
78
79
80
81
82
83
84
85
86
    layers = [[] for i in 1:length(layer_heights)]
    clayeri = []
    contour_trees = []

    # place contours in layers and construct KDTree for each contour
    for i in 1:length(cons)
        l = searchsorted(layer_heights, cons[i].pos[1,3])[1]
        push!(layers[l], i)
        push!(clayeri, l)
        add_vertex!(G)
        push!(contour_trees, KDTree(transpose(cons[i].pos)))
    end

87
    # loop through contours from previous layer and compare waypoints
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    for i in 1:length(cons)
        l = clayeri[i]

        # add contours from max_layers below
        if l > max_layers
            for c in layers[l-max_layers]
                add_edge!(G, c, i)
            end
        end

        if l == 1 || max_layers == 1
            continue
        end

        for c in layers[l-1]
            # if any points in contour i within min_dist of any points in contour c
            if any([length(b) > 0 for b in inrange(contour_trees[c], transpose(cons[i].pos), min_dist)])
                add_edge!(G, c, i) # mark i dependent on c
            end
        end
    end
109

110
    return contourdata(cons, G, layers, Dict(), layer_heights[1])
111
112
113
114
115
116
end


function seg_helper_orientation(p,q,r)
    val = (q[2]-p[2]) * (r[1]-q[1]) - (q[1]-p[1]) * (r[2]-q[2])
    if val > 0
117
        return 1 # clockwise
118
    elseif val < 0
119
        return 2 # anticlockwise
120
    else
121
        return 0 # colinear
122
123
124
125
    end
end


126
127
128
129
130
131
132
function onseg(p,q,r)
    # check if q lies on segment pr assuming 3 points are colinear
    return ((q[1] <= max(p[1], r[1])) && (q[1] >= min(p[1], r[1])) &&
    (q[2] <= max(p[2], r[2])) && (q[2] >= min(p[2], r[2])))
end


133
134
135
136
137
138
139
function seg_intersect(p1,q1,p2,q2)

    o1 = seg_helper_orientation(p1, q1, p2)
    o2 = seg_helper_orientation(p1, q1, q2)
    o3 = seg_helper_orientation(p2, q2, p1)
    o4 = seg_helper_orientation(p2, q2, q1)

140
141
142
143
144
    if (o1  o2) && (o3  o4) ||
        o1==0 && onseg(p1, p2, q1) ||
        o2==0 && onseg(p1, q2, q1) ||
        o3==0 && onseg(p2, p1, q2) ||
        o4==0 && onseg(p2, q1, q2)
145
146
147
148
149
150
        return true
    end

    return false
end

151

152
153
154
dist(p1, p2) = √sum((p1 -p2).^2)
interpolate(p1, p2, xi, axis) = p1 + (p2-p1)*(xi-p1[axis])/(p2[axis]-p1[axis])
interpolate(p1, p2, x1, xi, x2) = p1 + (p2-p1)*(xi-x1)/(x2-x1)
155

156

157
function voxmap(vox::Vector{Float64}, vox_d::Number, cdata::contourdata)
158
159
160

    # for one vox, get all contours which pass through it
    # only need to search contours in its layer
161
    l = Int(round((vox[3] + cdata.layer_height/2)/cdata.layer_height))
162
163
164
165
    voxx1 = vox[1] + vox_d/2
    voxx2 = vox[1] - vox_d/2
    voxy1 = vox[2] + vox_d/2
    voxy2 = vox[2] - vox_d/2
166

167
    seg_now = false
168
169
170
171
172
173
    seglen = Vector{Number}()
    segoffset = Vector{Number}()
    segcontours = Vector{Int}()
    seglen_sofar = 0
    t_start = 0

Jayant Khatkar's avatar
Jayant Khatkar committed
174
    if l > length(cdata.layers)
175
        return voxmap(seglen, segoffset, segcontours, 0)
Jayant Khatkar's avatar
Jayant Khatkar committed
176
177
    end

178
    for cid in cdata.layers[l]
179

180
        c = cdata.contours[cid]
181
182
183
184

        # check if contour passes thorough this vox
        for i in 2:size(c.pos)[1]

185
186
187
188
189
            # make sure it is a line segment, not a point
            if c.pos[i-1,1:2] == c.pos[i,1:2]
                continue
            end

190
191
192
193
            # is this line segment completely outside vox?
            if c.pos[i, 1] > voxx1 && c.pos[i-1, 1] > voxx1 ||
                c.pos[i,1] < voxx2 && c.pos[i-1, 1] < voxx2 ||
                c.pos[i,2] < voxy2 && c.pos[i-1, 2] < voxy2 ||
194
                c.pos[i,2] > voxy1 && c.pos[i-1, 2] > voxy1
195

196
                # segment outside vox entirely
197
                if seg_now
198
                    println("Something's gone wrong: segment entirely outside voxel, but last segment inside")
199
200
                end
                continue
201
            end
202

203
204
205
206
            p1inside = c.pos[i-1, 1] < voxx1 && c.pos[i-1, 1] > voxx2 && c.pos[i-1, 2] > voxy2 && c.pos[i-1, 2] < voxy1
            p2inside = c.pos[i, 1] < voxx1 && c.pos[i,1] > voxx2 && c.pos[i,2] > voxy2 && c.pos[i,2] < voxy1
            # is this line segment completely inside vox?
            if p1inside && p2inside
207

208
209
210
211
212
213
                seglen_sofar += dist(c.pos[i], c.pos[i-1]) # append to existing contour
                if !seg_now # start new seg
                    t_start = 0 #  0 bc contour must be starting for this case
                    seg_now = true

                    if i!=2
214
                        println("Whole segment inside but something wrong")
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
                    end
                    continue
                end
            end

            cross_side1 = seg_intersect(c.pos[i-1,:], c.pos[i,:], [voxx1, voxy1], [voxx1, voxy2])
            cross_side2 = seg_intersect(c.pos[i-1,:], c.pos[i,:], [voxx1, voxy1], [voxx2, voxy1])
            cross_side3 = seg_intersect(c.pos[i-1,:], c.pos[i,:], [voxx2, voxy1], [voxx2, voxy2])
            cross_side4 = seg_intersect(c.pos[i-1,:], c.pos[i,:], [voxx2, voxy2], [voxx1, voxy2])

            # does this line segment intersect with vox only once
            if p1inside  p2inside

                # find intersection point
                if cross_side1 || cross_side3
                    # intersection with x
                    xi = [voxx1, voxx2][[cross_side1, cross_side3]][1]
                    p_i = interpolate(c.pos[i-1,:], c.pos[i,:], xi, 1)
                    t_i = interpolate(c.time[i-1], c.time[i], c.pos[i-1,1], xi, c.pos[i,1])
234
                elseif cross_side2 || cross_side4
235
236
237
238
239
240
241
242
243
                    # intersection with y
                    yi = [voxy1, voxy2][[cross_side2, cross_side4]][1]
                    p_i = interpolate(c.pos[i-1,:], c.pos[i,:], yi, 2)
                    t_i = interpolate(c.time[i-1], c.time[i], c.pos[i-1,2], yi, c.pos[i,2])
                end

                if p1inside
                    # end existing segment
                    if !seg_now
244
245
246
                        # contour end on the first segment
                        t_start = 0
                        seglen_sofar = 0
247
248
249
250
251
252
253
                    end
                    seglen_sofar += dist(c.pos[i-1, :], p_i)
                    push!(segcontours, cid)
                    push!(seglen, seglen_sofar)
                    push!(segoffset, (t_i + t_start)/2)
                    seglen_sofar = 0
                    seg_now = false
254
                else
255
256
257
258
                    # start new contour
                    t_start = t_i
                    seglen_sofar = dist(p_i, c.pos[i, :])
                    seg_now = true
259
                end
260
                continue
261

262
263
264
265
266
            elseif sum([cross_side1, cross_side2, cross_side3, cross_side4]) >= 2
                # intersects twice
                p_is = []
                t_is = []
                if cross_side1
267
268
269
270
271
                    p = interpolate(c.pos[i-1,:], c.pos[i,:], voxx1, 1)
                    if !isnan(p[1])
                        push!(p_is, p)
                        push!(t_is, interpolate(c.time[i-1], c.time[i], c.pos[i-1,1], voxx1, c.pos[i,1]))
                    end
272
273
                end
                if cross_side2
274
275
276
277
278
                    p = interpolate(c.pos[i-1,:], c.pos[i,:], voxy1, 2)
                    if !isnan(p[1])
                        push!(p_is,p)
                        push!(t_is, interpolate(c.time[i-1], c.time[i], c.pos[i-1,2], voxy1, c.pos[i,2]))
                    end
279
280
                end
                if cross_side3
281
282
283
284
285
                    p = interpolate(c.pos[i-1,:], c.pos[i,:], voxx2, 1)
                    if !isnan(p[1])
                        push!(p_is,p)
                        push!(t_is, interpolate(c.time[i-1], c.time[i], c.pos[i-1,1], voxx2, c.pos[i,1]))
                    end
286
287
                end
                if cross_side4
288
289
290
291
292
                    p = interpolate(c.pos[i-1,:], c.pos[i,:], voxy2, 2)
                    if !isnan(p[1])
                        push!(p_is, p)
                        push!(t_is, interpolate(c.time[i-1], c.time[i], c.pos[i-1,2], voxy2, c.pos[i,2]))
                    end
293
                end
294

295
296
297
298
                if seg_now
                    print("Something's wrong")
                end

299
300
301
302
303
304
305
306
                if length(p_is) >= 2
                    push!(segoffset, mean(t_is))
                    push!(segcontours, cid)
                    if length(p_is) == 2
                        push!(seglen, dist(p_is[1], p_is[2]))
                    else
                        push!(seglen, dist(p_is[1], p_is[3]))
                    end
307
                else
308
309
310
311
312
313
314
315
                    p1inside = c.pos[i-1, 1] <= voxx1 && c.pos[i-1, 1] >= voxx2 &&
                            c.pos[i-1, 2] >= voxy2 && c.pos[i-1, 2] <= voxy1
                    p = p1inside ? c.pos[i-1,:] : c.pos[i,:]
                    t = p1inside ? c.time[i-1] : c.time[i]

                    push!(segcontours, cid)
                    push!(segoffset, (t + t_is[1])/2)
                    push!(seglen, dist(p_is[1], p))
316
                end
317
318
319
            end
        end

320
321
322
323
324
325
326
327
328
329
330
        # if contour ends inside the voxel
        if seg_now
            # end segment
            push!(segcontours, cid)
            push!(seglen, seglen_sofar)
            push!(segoffset, (t_start + last(c.time))/2)
            seglen_sofar = 0
            t_start = 0
            seg_now = false
        end

331
332
        # for those contours find exact segments
    end
333
    return voxmap(seglen./sum(seglen), segoffset, segcontours, Float64(segoffset  seglen)/sum(seglen))
334
335
end

336

337
338
339
function voxdata(fname::String, cdata::contourdata)
    voxels = DataFrames.DataFrame(CSV.File(fname))
    w = dist(Vector(voxels[1, ["x","y","z"]]), Vector(voxels[2, ["x","y","z"]]))
Jayant Khatkar's avatar
Jayant Khatkar committed
340
    println("Assumed width ", w)
341
342
343
344
345
346
347
348
349
    vpos = [[v.x, v.y, v.z] for v in eachrow(voxels)]
    voxms = [voxmap(v, w, cdata) for v in vpos]
    below = indexin([v - [0,0,cdata.layer_height] for v in vpos], vpos)
    replace!(below, nothing=>0)
    return voxdata(voxels, voxms, below, w)
end


function random_rollout(cdata::contourdata)
350
    done_contours = Set{Int}()
351
352
    avail_contours = Set(cdata.layers[1])
    todo_contours = Set(1:length(cdata.contours))
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    rollout = Vector{Int}()

    while length(avail_contours) > 0
        c = rand(avail_contours)
        push!(rollout, c)

        # remove selected contour from todo and avail, add to done
        delete!(avail_contours, c)
        delete!(todo_contours, c)
        push!(done_contours, c)

        # update available contours
        for i in todo_contours
            if i in avail_contours
                continue
368
            elseif length(inneighbors(cdata.G, i)) == 0
369
370
371
372
373
                push!(avail_contours, i)
                continue
            end

            add = true
374
            for j in inneighbors(cdata.G, i)
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
                if !(j in done_contours)
                    add = false
                    break
                end
            end

            if add
                push!(avail_contours, i)
            end
        end
    end

    return rollout
end


391
function valid_swap(rollout::Vector{Int}, i::Int, j::Int, cdata::contourdata)
392
393
394
    # would swapping indices i and j in rollout result in another valid rollout?
    # NOTE THIS FUNCTION DOESNT WORK
    # IT ONLY CHECKS DEPENDENCIES TO A DEPTH OF 1
395
    # TODO, leave for now, use check_validity to double check at the end
396
397
398
399
400
401
402
403
404

    if i>j
        i,j = j,i
    elseif i==j
        return true
    end

    c1 = rollout[i]
    c2 = rollout[j]
405
    c2_dependson = inneighbors(cdata.G, c2)
406
407
408
409
410

    if c1 in c2_dependson
        return false
    end

411
    c1_dependents = outneighbors(cdata.G, c1)
412
413
414
415
416
417
418
419
420
421
422
423
    c_between = rollout[i+1:j-1]

    for c in c_between
        if c in c1_dependents || c in c2_dependson
            return false
        end
    end

    return true
end


424
function check_validity(rollout::Vector{Int}, cdata::contourdata)
425
426
427
428
    # make sure a given rollout is valid
    done_contours = Set{Int}()

    for c in rollout
429
        c_dependson = inneighbors(cdata.G, c)
430
431
432
433
434
435
436
437
438
439
440

        if !issubset(c_dependson, done_contours)
            return false
        end

        push!(done_contours, c)
    end
    return true
end


441
442
443
444
445
446
function swap!(rollout::Vector{Int}, i::Int, j::Int)
    # swap values at ith and jth indices
    rollout[i], rollout[j] = rollout[j], rollout[i]
end


447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
function test_voxmap()
    # create vox
    vox = [0,0,0.5]
    vox_d = 2
    pos1 = [[0.5, -0.5] ones(2)*0.5 ones(2)]
    time1 = [0,1]
    pos2 = [[1.5, 0.5, -0.5, -1.5] ones(4)*0.5 ones(4)]
    time2 = Vector(0:3)
    pos3 = [[-0.5, -0.5] [2, -2] ones(2)]
    time3 = [0, 2.5]
    pos4 = [[0.5, 2.5] [-1.5, -0.5] ones(2)]
    time4 = [0,1]
    pos5 = [[-2,2] [-2,2] ones(2)]
    time5 = [0,1]
    contour1 = contour(pos1, time1)
    contour2 = contour(pos2,time2)
    contour3 = contour(pos3,time3)
    contour4 = contour(pos4,time4)
    contour5 = contour(pos5,time5)

    contours = [contour1, contour2, contour3, contour4, contour5]
468
469
    cdata = contourdata(contours, 1, 1)
    vm = voxmap(vox, vox_d, cdata)
470
    return vm
471
472
473
end


474
function rollout2time(rollout::Vector{Int}, cdata::contourdata)
475
    # start time of each contour, assuming no travel time
476
    return cumsum([cdata.contours[c].time[end] for c in rollout])
477
478
end

479
480
481
482
# Temperature function
T0 = 215 # extrusion temp
Tc = 25 # room temp
Tcutoff = 100 # temperature above which strain isn't happening
483
k = 0.08 #value unknown
484
485
486
487
488
Temp(t::Number) = Tc + (T0-Tc)*^(-k*t)
# see shape of temp function
#x = 1:100
#y = Temp.(x)
#plot(x,y)
489

490
function calc_cost(rollout::Vector{Int}, cdata::contourdata, vd::voxdata, mat::material)
491
492

    # go from rollout to timestart for each contour
493
    timestart = rollout2time(rollout, cdata)
494
495

    # calculate time at each voxel
496
    voxtimes = [sum(v.seglen.*(v.segoffset + timestart[v.segcontours]))/sum(v.seglen) for v in vd.maps]
497
498

    # calculate temp difference from voxel below it
499
500
501
    considered_voxels = (1:length(vd.below))[(vd.below.!=0) .& (.!isnan.(voxtimes))] # cannot calculate cost is no voxel underneath
    considered_voxels = considered_voxels[.!isnan.(voxtimes[vd.below[considered_voxels]])]
    Δt = voxtimes[considered_voxels] - voxtimes[vd.below[considered_voxels]]
502
    ΔT = Tcutoff .- Temp.(Δt)
503
    replace!(x-> x<0 ? 0 : x, ΔT)
504
505

    # calculate stresses at each voxel
506
507
508
509
510
    F = (2/mat.σ̄[1,1]^2 - 1/mat.σ̄[3,3]^2)/2
    G = 1/(2*mat.σ̄[3,3]^2)
    L = 1/(2*mat.σ̄[1,2]^2)
    M = 1/(2*mat.σ̄[1,3]^2)
    rel_voxels = vd.voxels[considered_voxels,:]
511
512

    # calculate cost func at each voxel
513
514
515
516
517
518
519
520
521
522
523
    σ11 = rel_voxels.Sx + mat.E*mat.α*ΔT
    σ22 = rel_voxels.Sy + mat.E*mat.α*ΔT
    σ33 = rel_voxels.Sz
    σ12 = rel_voxels.Txy
    σ23 = rel_voxels.Tyz + (cdata.layer_height/vd.width)*mat.E*mat.α*ΔT
    σ31 = rel_voxels.Txy + (cdata.layer_height/vd.width)*mat.E*mat.α*ΔT
    cost = F * (σ11 - σ22).^2 +
        G * ((σ33 - σ11).^2 + (σ33 - σ22).^2) +
        2 * L * (σ12).^2 +
        2 * M * (σ23 + σ31).^2 .- 1.0
    return sum(cost)
524
525
526
end


527
function construct_cost(cdata::contourdata, vd::voxdata, mat::material)
528
529
    # store contour time lengths inside function
    contour_times = [cdata.contours[c].time[end] for c in 1:length(cdata.contours)]
530

531
532
    # considered voxels
    not_empty_voxels = length.([m.seglen for m in vd.maps]) .>0
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
    valid_voxels = (1:length(vd.below))[(vd.below.!=0) .& not_empty_voxels]
    valid_voxels = valid_voxels[not_empty_voxels[vd.below[valid_voxels]]]

    #stress_size = .√( vd.voxels.Sx.^2 + vd.voxels.Sy.^2 + vd.voxels.Sz.^2)
    #top_voxes = Set(sortperm(stress_size)[1:Int(length(stress_size)/4)]) # top stressors only
    #top_valid_voxels = sort(collect(Set(valid_voxels) ∩ top_voxes))
    #rel_voxels = vd.voxels[top_valid_voxels,:]

    #relmaps = sort(collect(Set(vd.below[top_valid_voxels]) ∪ Set(top_valid_voxels)))
    #considered_voxels = indexin(top_valid_voxels, relmaps)
    # relbelows = indexin(vd.below[top_valid_voxels], relmaps)
    considered_voxels = valid_voxels
    relbelows = vd.below[valid_voxels]
    rel_voxels = vd.voxels[considered_voxels,:]
    relmaps = vd.maps
548

549
550
551
552
553
554
    # calculate stresses at each voxel
    F = (2/mat.σ̄[1,1]^2 - 1/mat.σ̄[3,3]^2)/2
    G = 1/(2*mat.σ̄[3,3]^2)
    L = 1/(2*mat.σ̄[1,2]^2)
    M = 1/(2*mat.σ̄[1,3]^2)

555
    return quote
556
557
558
559
560
        function cost_f(rl::Vector{Int})
            # println("Cumulative Sum") # 100k
            timestart = cumsum([$contour_times[c] for c in rl])

            #println("Vox times") # 600
561
            voxtimes = [v.seglen  timestart[v.segcontours] + v.c for v in relmaps]
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583

            # println("time diff") # 28k
            Δt = voxtimes[considered_voxels] - voxtimes[relbelows]

            #println("Temp diff") # 6k
            ΔT = Tcutoff .- (Tc .+ $(T0-Tc).*.^(-k.*Δt))

            # println("Temp diff clean") # 82k
            replace!(x-> x<0 ? 0 : x, ΔT)

            # println("Stresses") # 6k
            σ11 = rel_voxels.Sx + $(mat.E*mat.α)*ΔT
            σ22 = rel_voxels.Sy + $(mat.E*mat.α)*ΔT
            σ33 = rel_voxels.Sz
            σ12 = rel_voxels.Txy
            σ23 = rel_voxels.Tyz + $((cdata.layer_height/vd.width)*mat.E*mat.α)*ΔT
            σ31 = rel_voxels.Txy + $((cdata.layer_height/vd.width)*mat.E*mat.α)*ΔT
            cost = sum($F * (σ11 - σ22).^2 +
                $G * ((σ33 - σ11).^2 + (σ33 - σ22).^2) +
                $(2 * L) * (σ12).^2 +
                $(2 * M) * (σ23 + σ31).^2)
            return cost
584
585
        end
    end
586
587
end

588

Jayant Khatkar's avatar
Jayant Khatkar committed
589
590
591
592
593
594
595
596
function clean_contour(c::contour)
    # remove first element of array if second element is the same
    while c.pos[1,:] == c.pos[2,:]
        c.pos = c.pos[2:end, :]
    end
    return c
end

597
598
599
600
601
602
603
604
605
606
607
608

function stress_multiplier!(a::DataFrame, mul::Number)
    a.Sx = a.Sx*mul
    a.Sy = a.Sy*mul
    a.Sz = a.Sz*mul
    a.Txy = a.Txy*mul
    a.Tyz = a.Tyz*mul
    a.Txz = a.Txz*mul
    return
end


609
# ABS material properties
610
611
612
α_ABS = 10e-6#100      # 78 - 108      #10-6
E_ABS = 2.5e9    # 1.19e9 - 2.9e9
σ̄ = 6e7          # mega
613
σ̄_ABS = [
614
615
616
    [σ̄       σ̄*0.5   σ̄*0.375]
    [σ̄*0.5   σ̄       σ̄*0.375]
    [σ̄*0.375 σ̄*0.375 σ̄*0.75 ]
617
618
619
    ]
ABS = material(α_ABS, E_ABS, σ̄_ABS)

620

Jayant Khatkar's avatar
Jayant Khatkar committed
621
622
obj = "/Users/jayant/phd/tempaware/" * "M1"
contours = clean_contour.(contour.(JSON.parse(open(obj * "contours.json"))))
623
cdata = contourdata(contours, 5, 5) # contour data
624
@time vd = voxdata(obj * "_voxels.csv", cdata)
625
rl = random_rollout(cdata)
626
627
628
629
630
631
632
633
calc_cost(rl, cdata, vd, ABS) # 500/second


# local search loop
o_rl = copy(rl)
n = length(rl)
k = 5
cost_val = Inf
634
o=0
635
@time for l in 1:100
636
637
638
639
640
641
642
    println(l)
    println(cost_val)
    costs = Dict()
    for i in 1:n-1
        for j in i+1:min(i+k,n)
            if valid_swap(rl, i, j, cdata)
                swap!(rl, i, j)
643
                costs[i,j] = cost_f(rl)
644
                swap!(rl, i, j)
645
                o += 1
646
647
648
649
650
651
652
653
            end
        end
    end
    v, (i,j) = findmin(costs)
    if v < cost_val
        cost_val = v
        swap!(rl, i, j)
    end
654
end
655
656
657
658
659
660
661
662
println(o)


### Visualise distribution of stresses
data = .( vd.voxels.Sx.^2 + vd.voxels.Sy.^2 + vd.voxels.Sz.^2)
data = .(vd.voxels.Txy.^2 + vd.voxels.Tyz.^2 + vd.voxels.Txz.^2)
histogram(data) # vast majority of voxels near 0 stress - can ignore
histogram!(sort(data, rev=true)[1:4000]) # vast majority of voxels near 0 stress - can ignore