Determining the number of turtle-clusters - oop

I have been trying to calculate the number of turtle-clusters in my World but I have been constantly faced with "You can't use GROUPE in a patch context, because GROUPE is turtle-only". I am using bits from the Segregation model of Schelling and adapting the Patch Clusters Example from the Model Library, but I have not been able to get the number of clusters by using the command show max [amas] of personnes after running the model.
The line causing problems is towards the bottom of the bloc and is:
(groupe = [groupe] of myself)]
Here is the full code:
extensions
[
GIS ; Extension GIS
]
globals
[
v
;vc
routes.data ; shapefile routes
Usol.data ; shapefile utilisation sol
average-happy ; pourcentage heureux
amas
]
patches-own
[
routes ; routes
routes? ; booléenne routes
Usol
Usol?
state ; état d'une patch
val ; valeur
cluster
]
turtles-own
[
groupe
unhappy?
counter
similar-nearby
other-nearby
total-nearby
happy
]
breed ; Création d'une classe
[
personnes
personne
]
to setup ; Déclaration de la procédure setup
ca ; Clear-all
reset-ticks ; Remet le compteur de ticks à zéro
set v 2
initialiserGIS ; Initialisation de la procédure initialiserGIS
creerHumains
do-plots
end ; Fin de la procédure setup
to initialiserGIS ; Déclaration de la procédure initialiserGIS
set Usol.data gis:load-dataset "utilisationDuSol.shp"
gis:apply-coverage Usol.data "LANDUSE" Usol
ask patches
[
set Usol? FALSE
]
ask patches gis:intersecting Usol.data
[
set Usol? TRUE
ifelse Usol = "residential"
[
set state 1
set pcolor green
]
[
set state 0
set pcolor grey
]
]
set routes.data gis:load-dataset "routesMtl.shp"
ask patches
[
set routes? FALSE
]
ask patches gis:intersecting routes.data
[
set routes? TRUE
set state 0 ; Empêche aux agents d'habiter sur les routes
set pcolor red ; Assigne la couleur rouge aux routes
]
end ; Fin de la procédure initialiser GIS
to creerHumains ; Déclaration de la procédure creerHumains
ask patches with [state = 1] ; Demande aux cellules résidentielles
[
set val random-float 1 ; Accorde une valeur aléatoire décimale entre 0 et 1 à la variable val
]
let vide 0.1 ; Initialisation de la variable locale vide avec la valeur 0.1
let limite1 (1 - vide) / v ; Initialisation de la variable locale limite
let residents patches with [state = 1 and val > vide] ; Initialisation de la variable locale residents
ask residents ; Demande aux residents
[
sprout-personnes 1 ; Primitive permettant à une patch de créer un agent sur toutes les patches résidentielles
] ; Permet de créer un nombre identique de personne de chaque groupe
let limiteList (list (pmin * (1 - vide )) ((1 - pmin) * (1 - vide)))
let i 0
let minVal vide
let maxVal 0
while [i <= v - 1]
[
set maxVal minVal + item i limiteList
ask personnes with [val <= maxVal and val > minVal]
[
set groupe i + 1
]
set minVal maxVal
set i i + 1
]
ask personnes ;ceci sert uniquement à attribuer une couleur différente à chaque groupe
[ ; Assigne la couleur et la forme appropriée en fonction du groupe
ifelse groupe = 1
[
set color red
set shape "house"
]
[
ifelse groupe = 2
[
set color blue
set shape "house"
]
[
ifelse groupe = 3
[
set color green
set shape "house"
]
[
ifelse groupe = 4
[
set color orange
set shape "house"
]
[
ifelse groupe = 5
[
set color black
set shape "house"
]
[
ifelse groupe = 6
[
set color brown
set shape "house"
]
[
ifelse groupe = 7
[
set color pink
set shape "house"
]
[
ifelse groupe = 8
[
set color white
set shape "house"
]
[
set color magenta
set shape "house"
]
]
]
]
]
]
]
]
]
end ; Fin de la procédure creerHumains
to move ; Déclaration de la procédure move
move-to one-of patches with [Usol = "residential"]
if any? other turtles-here
[
move ;; Continue jusqu'à tant qu'une patch soit trouvée
]
end
to update-variables ; Déclaration de la procédure update-variables ; permet de mettre à jour les valeurs
update-turtles
update-globals
end ; Fin de la procédure update-variables
to update-turtles ; Déclaration de la procédure update-turtles
ask turtles ; demande turtles
[ ; Test des patches voisines
set counter 0 ; réinitialise counter
set similar-nearby count (turtles-on neighbors) with [groupe = [groupe] of myself]
set other-nearby count (turtles-on neighbors) with [groupe != [groupe] of myself]
set total-nearby similar-nearby + other-nearby
ifelse groupe = 1
[
ifelse (Tmin >= similar-nearby) ; vérification si vc est supérieur ou égale aux voisins similaires
[ ; personne unhappy + move
set unhappy? TRUE
set happy 0
move
]
[ ; personne happy
set unhappy? FALSE
set happy 1
]
]
[
ifelse (Tmaj <= similar-nearby) ; vérification si vc est supérieur ou égale aux voisins similaires
[ ; personne unhappy + move
set unhappy? TRUE
set happy 0
move
]
[ ; personne happy
set unhappy? FALSE
set happy 1
]
]
]
end ; Fin de la procédure update-turtles
to update-globals ; Déclaration de la procédure update-globals
set average-happy mean [happy] of turtles ; Average-happy = moyenne des turtles happy
end ; Fin de la procédure update-globals
to go ; Déclaration de la procédure go
update-variables ; Vérifie l'état de chacunes des personnes et fait bouger celles nécessitant de l'être
tick ; Incrémente la valeur de la variable tick
if ticks >= 100 ; Si le nombre de ticks est supérieur ou égal à 100
[
stop ; Arrête le modèle
]
if c-unhappy = 0
[
stop ; Arrête le modèle si personne est unhappy
]
end ; Fin de la procédure go
to do-plots ; Déclaration de la procédure do-plots
plot average-happy * 100 ; Plot la moyenne des habitants étant happy
end ; Fin de la procédure do-plots
to-report c-happy ; Déclaration de la procédure de rapportage c-happy
report sum [happy] of turtles ; Rapporte le nombre de turtles étant happy
end ; Fin de la procédure de rapportage c-happy
to-report c-unhappy ; Déclaration de la procédure de rapportage c-unhappy
report ((count turtles) - (sum [happy] of turtles)) ; Rapporte le nombre de turtles étant unhappy
end ; Fin de la procédure de rapportage c-unhappy
;;; Q6
to find-clusters
loop
[
;; pick a random patch that isn't in a cluster yet
let seed one-of personnes with [cluster = nobody]
;; if we can't find one, then we're done!
if seed = nobody
[
show-clusters
stop
]
;; otherwise, make the patch the "leader" of a new cluster
;; by assigning itself to its own cluster, then call
;; grow-cluster to find the rest of the cluster
ask seed
[
set cluster self
grow-cluster
]
]
display
end
to grow-cluster ;; patch procedure
ask neighbors4 with [(cluster = nobody) and
(groupe = [groupe] of myself)]
[
set cluster [cluster] of myself
grow-cluster
]
end
;; once all the clusters have been found, this is called
;; to put numeric labels on them so the user can see
;; that the clusters were identified correctly
to show-clusters
let counter2 0
loop
[ ;; pick a random patch we haven't labeled yet
let p one-of patches with [plabel = ""]
if p = nobody
[
stop
]
;; give all patches in the chosen patch's cluster
;; the same label
ask p
[
ask personnes with [cluster = [cluster] of myself]
[
set amas counter2
]
]
set counter2 counter2 + 1
]
end

Related

Awk - print the number of row between a selected range from variable in awk and increment his value when variable change after user keypress

This question is more further developed with reference to the following case awk print the number of columns between a selected range from awk
I have the next short script:
#!/bin/bash
#Control del buffer
#awk en stackowerflow
#https://stackoverflow.com/questions/74483916/awk-print-the-number-of-columns-between-a-selected-range-from-awk/74483975?noredirect=1#comment131485506_74483975
if [ $# -eq 1 ]; then
FICH="${1}"
else
FICH="donaciones"
fi
#_INIT valores globales para mostrar debajo en la ultima linea
#alto_INIT necesario para poner texto abajo en la ultima linea
alto_INIT=`tput lines`
alto=`expr $alto_INIT - 2`
largo=`tput cols`
TOTAL_LINEAS_INIT=`cat "$FICH" | wc -l`
TOTAL_LINEAS=$TOTAL_LINEAS_INIT
#Mostramos solo las lineas dependiendo del alto del terminal
#Numero de paginas que hay que mostrar
LINEA=`expr $TOTAL_LINEAS - $alto`
NUM_PAG=`echo "scale=1; $TOTAL_LINEAS / $alto"|bc`
#Si el sresto de dividdir NPAG entre n lineas es +0 sumanos 1 pag. mas
if [ "${NUM_PAG##*.}" -gt 0 ]; then
NUM_PAG=`echo "scale=0; ${NUM_PAG}" + 1 |bc`
NUM_PAG=${NUM_PAG%%.*}
fi
buffer=`awk -v total_lineas="$TOTAL_LINEAS" -v linea="$LINEA" 'NR>=linea&&NR<=total_lineas' "$FICH"`
function Arriba(){
TOTAL_LINEAS=`expr $TOTAL_LINEAS - $alto`
DESDE=`expr $TOTAL_LINEAS - $alto`
HASTA=$TOTAL_LINEAS
if [[ $DESDE -lt 0 ]] ; then
DESDE=0
HASTA=`expr $DESDE + $alto`
fi
buffer=`awk -v desde="$DESDE" -v hasta="$HASTA" 'NR>=desde&&NR<=hasta' "$FICH"`
TOTAL_LINEAS=`expr $HASTA + 1`
}
function Abajo(){
DESDE=$TOTAL_LINEAS
HASTA=`expr $TOTAL_LINEAS + $alto`
if [[ $HASTA -gt $TOTAL_LINEAS_INIT ]] ; then
HASTA=$TOTAL_LINEAS_INIT
fi
buffer=`awk -v desde="$DESDE" -v hasta="$HASTA" 'NR>=desde&&NR<=hasta' "$FICH"`
TOTAL_LINEAS=$HASTA
}
while true; do
clear
printf "$buffer"
tput cup $alto_INIT 0 && printf "Total Lineas: $TOTAL_LINEAS_INIT | Total Pag: $NUM_PAG |Buffer: De $DESDE hasta $HASTA | $TOTAL_LINEAS | (w) Ayuda"
read -rsn1 TECLA
case $TECLA in
h) Arriba ;;
j) Abajo ;;
w) Help ;;
q) printf "\n" && break ;;
esac
done
exit 0
The goal here is show the number of line from a range of lines invoked by awk.
The program calculate the global lines of terminal and made a pagination from a file.Like
less, but i want to show only the portion of the file when the user press a "h" or "j" key. Every time the user press the key "h" the buffer ( portion of file) change and show
the correct part of file in dependence of number of rows. And when the user press the "j" key the buffer return to the previous key.
The program works ok but i want that when awk show the buffer , give me the number of line that correspond to this global line of the file. For this, i have the variable $TOTAL_LINEAS that increment or decrement every instruction buffer change. And this buffer instruction show from this TOTAL_LINEAS until the lines of terminal , and this every time the user press key. In the previous answer i can to add this number of line
but when the user press a key for change the new buffer text allways print the number for this buffer but not for the global buffer that correspond to real line of the file. In other words, allways print the number of line but in this portion of text not for the global text.
I.E: if i have
1 1:20220413:20:Curso Astrología:5:Vicente Ferrer
2 1:10042022:0:Donación instituto Samye:103:Propia
3 14:20220428:0:Candelario Yeshe Nyimpo Inc:9:Dudjom Tersar
4 1:20220512:60:Ayuda por el Hambre y Violencia:6:Vicente Ferrer
Total Lineas: 43 | Total Pag: 2 |Buffer: De 0 hasta 26 | 27
but in the next keypress for go to the next page i need:
5 1:20220413:20:111
6 1:10042022:0:22
7 14:20220428:0:33
8 1:20220512:60:44
Total Lineas: 43 | Total Pag: 2 |Buffer: De 27 hasta 43 | 43
and not:
1 1:20220413:20:111
2 1:10042022:0:22
3 14:20220428:0:33
4 1:20220512:60:44
Total Lineas: 43 | Total Pag: 2 |Buffer: De 27 hasta 43 | 43
Finally was easy:
buffer=`echo "$buffer" |awk -v i=$TOTAL_LINEAS 'NR==i !NF{print;next} NF{print ++i, $0}'`
Thanks all !!

I am extracting data from a Json in SQL and the data comes in lists, how do I get it from there?

thanks for reading it!
I am extracting data from a Json with operators in SQL, this is the code:
select lc.name as company,
lr.name as retailer,
ls.name as tienda,
sm.created_on as date,
sm.task_id as task_id,
ss.submission_data::json-> '¿Qué ''bancos'' se encuentran cerca de la tienda? De ser necesario, pregunta al gerente de tienda' AS banco,
ss.submission_data::json->> 'Indica la distancia aproximada entre la tienda y el ''banco'' más cercano' AS banco_distancia,
ss.submission_data::json->> '¿En la zona hay disponibilidad de ''transporte público''? Indica los tipos de transporte' AS transporte,
ss.submission_data::json->> 'Indica el precio estimado de un viaje en ''transporte público''' AS transporte_precio,
ss.submission_data::json->> '¿En la zona hay servicio de ''aplicaciones de envíos''?' AS app_envio
from submission_submissionmetadata sm
left join submission_submission ss on sm.submission_id = ss.id
left join location_store ls on ls.id = sm.store_id
left join location_retailer lr on lr.id = ls.retailer_id
left join location_company lc on lc.id = lr.company_id
where sm.brand_id = 293
order by date desc
In The results I get the columns bank, transport and app_ship come as in a list type, I have tried to use functions to flatten this but I have not been successful. Do you know what I can do?
https://www.postgresql.org/docs/current/functions-json.html
Waiting on your response to comment above, but you can see all the ways to extract json in the above doc. For instance,if you want only the first element of the app_envio array, it would be:
ss.submission_data::json #>> '{'¿En la zona hay servicio de ''aplicaciones de envíos''?',0}' AS app_envio

Recursive query to give a route in postgreSQL

I have to do a recursive function in pSQL to get the following query:
I have a table called tb_route with from_city and to_city
I have another column with the distance in km between different cities.
The table is builded recursively. I have to make a recursive CTE to show the route between two cities (i.e., from 'Santiago de compostela' to 'Saint Jean Pied de Port') showing the total km of the route and the cities where it goes through.
The output has to be something like this:
This is what I've tried:
WITH RECURSIVE cities AS (
SELECT *
FROM textil.tb_route
WHERE to_city_name = 'Santigo de Compostela'
UNION ALL
SELECT e.from_city, e.to_city, e.route, e.km
FROM textil.tb_route e
INNER JOIN cities tb_route ON tb_route.from_city_name = e.from_city
)
SELECT *
FROM cities;
And I had an error like:
ERROR: column e.from_city does not exist
LINE 8: ...JOIN cities tb_route ON tb_route.from_city_name = e.from_cit...
Table:
CREATE TABLE textil.tb_route
(
from_city_name CHARACTER VARYING(120) NOT NULL ,
to_city_name CHARACTER VARYING(120) NOT NULL ,
km_distance_num NUMERIC(5,2) NOT NULL ,
CONSTRAINT pk_route PRIMARY KEY (from_city_name, to_city_name)
);
Data:
INSERT INTO textil.tb_route VALUES
('Saint Jean Pied de Port','Roncesvalles',25.7),
('Somport','Jaca',30.5),
('Roncesvalles','Zubiri',21.5),
('Jaca','Arrés',25),
('Zubiri','Pamplona/Iruña',20.4),
('Arrés','Ruesta',28.7),
('Pamplona/Iruña','Puente la Reina/Gares',24),
('Ruesta','Sangüesa',21.8),
('Puente la Reina/Gares','Estella/Lizarra',22),
('Sangüesa','Monreal',27.25),
('Estella/Lizarra','Torres del Río',29),
('Monreal','Puente la Reina/Gares',31.1),
('Torres del Río','Logroño',20),
('Logroño','Nájera',29.6),
('Nájera','Santo Domingo de la Calzada',21),
('Santo Domingo de la Calzada','Belorado',22.7),
('Belorado','Agés',27.4),
('Agés','Burgos',23),
('Burgos','Hontanas',31.1),
('Hontanas','Boadilla del Camino',28.5),
('Boadilla del Camino','Carrión de los Condes',24.6),
('Carrión de los Condes','Terradillos de los Templarios',26.6),
('Terradillos de los Templarios','El Burgo Ranero',30.6),
('El Burgo Ranero','León',37.1),
('León','San Martín del Camino',25.9),
('San Martín del Camino','Astorga',24.2),
('Astorga','Foncebadón',25.9),
('Foncebadón','Ponferrada',27.3),
('Ponferrada','Villafranca del Bierzo',24.1),
('Villafranca del Bierzo','O Cebreiro',28.4),
('O Cebreiro','Triacastela',21.1),
('Triacastela','Sarria',18.3),
('Sarria','Portomarín',22.4),
('Portomarín','Palas de Rei',25),
('Palas de Rei','Arzúa',28.8),
('Arzúa','Pedrouzo',19.1),
('Pedrouzo','Santiago de Compostela',20),
('Bayona','Ustaritz',14.3),
('Ustaritz','Urdax',21.2),
('Urdax','Elizondo',18.8),
('Elizondo','Berroeta',9.7),
('Berroeta','Olagüe',20.4),
('Olagüe','Pamplona/Iruña',25),
('Irún','Hernani',26.6),
('Hernani','Tolosa',18.9),
('Tolosa','Zerain',33),
('Zerain','Salvatierra/Agurain',28),
('Salvatierra/Agurain','Vitoria/Gasteiz',27.4),
('Vitoria/Gasteiz','La Puebla de Arganzón',18.5),
('La Puebla de Arganzón','Haro',31),
('Haro','Santo Domingo de la Calzada',20),
('Bayona','Irún',33.8),
('Tolosa','Zegama',37.9),
('Zegama','Salvatierra/Agurain',20.1),
('La Puebla de Arganzón','Miranda del Ebro',22.3),
('Miranda del Ebro','Pancorbo',16.7),
('Pancorbo','Briviesca',23.4),
('Briviesca','Monasterio de Rodilla',19.8),
('Monasterio de Rodilla','Burgos',28.5);
```
Here I leave the solution I've get finally:
with recursive caminos(from_city_name, to_city_name, path, total_distance, terminar, ultima_ciudad) as (
-- Consulta base
select to_city_name
,'Saint Jean Pied de Port' -- Cambiar Destino
,concat(to_city_name, concat(' -> ', from_city_name))
,cast(km_distance_num as numeric(8,2))
,0 --No terminar
,from_city_name
from textil.tb_route
where to_city_name = 'Santiago de Compostela' -- Cambiar Origen
union all
-- Consulta recursiva
select caminos.from_city_name
,caminos.to_city_name
,concat(caminos.path, concat( ' -> ', tr.from_city_name))
,cast(caminos.total_distance + tr.km_distance_num as numeric(8,2))
,case when tr.from_city_name = caminos.to_city_name then 1 else 0 end
,tr.from_city_name
from caminos inner join textil.tb_route tr on tr.to_city_name = caminos.ultima_ciudad and caminos.terminar != 1
)
select from_city_name, to_city_name, path, total_distance
from caminos
where 1 = 1
and from_city_name = 'Santiago de Compostela' --Cambiar Origen
and ultima_ciudad = 'Saint Jean Pied de Port' -- Cambiar Destino
;
I understand your question as a graph-walking problem. As described in your questions, edges are directed (meaning that you can travel from from_city_name to to_city_name, but not the other way around).
Here is an approach using a recursive CTE. The idea is to start from a given city, and then follow all possible routes, while keeping track of the overall travel path in an arry. The recursion stops either when a circle is detected, or when the target city is reached. Then, the outer query filters on the successful paths (there may be none, one or several).
with recursive cte as (
select
from_city_name,
to_city_name,
km_distance_num,
array[from_city_name::text, to_city_name::text] path
from tb_route
where from_city_name = 'Saint Jean Pied de Port'
union all
select
r.from_city_name,
r.to_city_name,
c.km_distance_num + r.km_distance_num,
c.path || r.to_city_name::text
from tb_route r
inner join cte c on c.to_city_name = r.from_city_name
where
not r.to_city_name = any(c.path)
and c.from_city_name <> 'Santiago de Compostela'
)
select
path[1] from_city_name,
to_city_name,
km_distance_num,
array_to_string(path, ' > ') path
from cte
where to_city_name = 'Santiago de Compostela';
Demo on DB Fiddle:
from_city_name | to_city_name | km_distance_num | path
:---------------------- | :--------------------- | --------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Saint Jean Pied de Port | Santiago de Compostela | 775.3 | Saint Jean Pied de Port > Roncesvalles > Zubiri > Pamplona/Iruña > Puente la Reina/Gares > Estella/Lizarra > Torres del Río > Logroño > Nájera > Santo Domingo de la Calzada > Belorado > Agés > Burgos > Hontanas > Boadilla del Camino > Carrión de los Condes > Terradillos de los Templarios > El Burgo Ranero > León > San Martín del Camino > Astorga > Foncebadón > Ponferrada > Villafranca del Bierzo > O Cebreiro > Triacastela > Sarria > Portomarín > Palas de Rei > Arzúa > Pedrouzo > Santiago de Compostela

Can a turtle variable "logged" for different patches?

[ifelse ( random-float 1 < 0.99 ) [
set security-apprehension security-apprehension + 1 ][
set successful-shoplifts successful-shoplifts + 1 ]
The above is from a section of coding related to shoplifter behaviour and shows two turtles-own variables (security-apprehension and successful-shoplifts), one of which will increase and the other remain the same. This can only occur when a turtle is on a certain patch (A store). I would like 'security-apprehension' to resort back to 0 when the turtle is not on that patch and for the score to be 'logged' i.e. go back to what it was previously when the turtle is back on the patch so I can set a criteria to determine whether a shoplifter should be considered a prolific offender to individual stores.
How can this be achieved?
I'm not 100% sure on the output you're after, but here's an attempt that makes use of the table extension to build a turtle-specific dictionary to store patch coordinates as a key paired with the security apprehension level of the corresponding patch.
First, the setup:
extensions [ table ]
turtles-own [ security-table current-security-apprehension]
to setup
ca
ask n-of 20 patches [
set pcolor green
]
crt 1 [
setxy random-xcor random-ycor
set security-table table:make
set current-security-apprehension "NA"
]
reset-ticks
end
Now, you can have your turtles check if they're at a 'store'. If they are, check if the store already has an associated security apprehension level- if it does not, assign one. Then, query that table to get the appropriate security apprehension level for the current store (more details in comments).
to go
ask turtles [
set current-security-apprehension "NA"
rt random 91 - 45
fd 1
; If you're at a 'store'
if [ pcolor ] of patch-here = green [
; Use the pxcor-pycor pair in a list as a dictionary
; key to store/check security apprehension in a table
let this-key list pxcor pycor
; Check if the store has been visited
if not table:has-key? security-table this-key [
; If not, store the security value for this store
; (randomly chosen, in this example- how you set this
; depends on your model)
table:put security-table this-key one-of [ "high" "medium" "low" ]
]
; Get the security apprehension level for the current patch
set current-security-apprehension table:get security-table this-key
]
if current-security-apprehension != "NA" [
show ( word "Security apprehension on " patch-here " is " current-security-apprehension )
]
]
tick
end
A modified version of the above as per clarification in comments:
extensions [ table ]
turtles-own [ security-table shoplift-table current-security-apprehension]
to setup
ca
ask n-of 20 patches [
set pcolor green
]
crt 1 [
setxy random-xcor random-ycor
set security-table table:make
set shoplift-table table:make
set current-security-apprehension 0
]
reset-ticks
end
to go
ask turtles [
set current-security-apprehension "NA"
rt random 91 - 45
fd 1
; If you're at a 'store'
if [ pcolor ] of patch-here = green [
; Use the pxcor-pycor pair in a list as a dictionary
; key to store/check security apprehension in a table
let this-key list pxcor pycor
; Check if the store has been visited, add shoplift
; and security values as needed
if not table:has-key? security-table this-key [
table:put security-table this-key 0
table:put shoplift-table this-key 0
]
; Try to shoplift- if random value 0-1 is less than
; 0.98, count as a success. Otherwise, add one to
; security score
ifelse random-float 1 < 0.98 [
; Increase the current shoplifting value by one
let cur-shop table:get shoplift-table this-key
table:put shoplift-table this-key cur-shop + 1
] [
; Otherwise, increase the security apprehension by 1
let cur-sec table:get security-table this-key
table:put security-table this-key cur-sec + 1
print "Caught you red-handed."
; Check if they have been caught here 2 or more times:
if table:get security-table this-key >= 2 [
print "CALL THE POLICE!"
]
]
]
]
tick
end

how to move turtles to sequential targets and stop at endpoints

For clarification on this question, here is the original question with background information.
I have been attempting to make one agentset (ships) move towards another agentset (target-port) and once the ships arrive, move on to the next target (shortest distance away). What i have so far although its not working correctly:
ask ships
[ if distance target-port = 0
[ set target-port min-one-of ports with [who != myself] [distance myself]
face target-port ]
ifelse distance target-port < 1
[ move-to target-port ]
[ fd 1 ]
]
I would also like to have the ships stop moving once they've met the end of the path. (i.e port 0 or 2 in this specific scenario).
Here is an example of the entire code to make it easier to understand:
breed [ships ship]
breed[ports port]
ships-own [current-port target-port]
to setup
clear-all
let index 0
create-ports 3
[
let loc item index [ [4 -4] [ 9 5] [ -11 11] ]
setxy (item 0 loc) (item 1 loc)
set index index + 1
set shape "circle"
set size 5
set color red - 1]
ask ports
[let s who
set label ( word " Port " s )
hatch-ships 1
[ set current-port s
set size 10
set color red
pen-down
set pen-size 1
Set target-port min-one-of ports with [ who != s] [distance myself]
set heading towards target-port
set label (word "target " target-port)
] ]
reset-ticks
end
to go
ask ships
[ if distance target-port = 0
[ set target-port min-one-of ports with [who != myself] [distance myself]
face target-port ]
ifelse distance target-port < 1
[ move-to target-port ]
[ fd 1 ]
]
end
Any help would be greatly appreciated. Thanks
For the first part of your question, you just need to use other.
ask ships [
if (distance target-port = 0) [
let _otherports no-turtles
ask target-port [set _otherports (other ports)]
set target-port min-one-of _otherports [distance myself]
face target-port
]
ifelse (distance target-port < 1) [
move-to target-port
][
fd 1
]
]
You do not really provide enough info to answer the rest of your question, since your code forces ships to pick a new target once they arrive at their current target. One way to proceed is to give a ship a list of ports to visit, in order, and then stop when you reach the end of the list.