Логотип Qgis Syntax Expressions

Qgis Syntax Expressions

Организация
Impertio-Studio
qgis-syntax-expressions

Use when writing QGIS expressions for filtering, labeling, symbology, or field calculations. Prevents expression syntax errors and context misconfiguration. Covers QgsExpression parsing, evaluation contexts, field calculator, data-defined properties, and custom functions. Keywords: QgsExpression, expression, field calculator, label expression, data-defined, @qgsfunction, filter, evaluate, calculate field, formula, conditional label, dynamic value.

Обзор

ИздательImpertio-Studio
РепозиторийQGIS-Claude-Skill-Package
Название навыкаqgis-syntax-expressions
Звёзды
39
Форки
2
Файлы в комплекте
3
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 3

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — Impertio-Studio. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Qgis Syntax Expressions в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/Impertio-Studio/QGIS-Claude-Skill-Package/tree/main/skills/source/qgis-syntax/qgis-syntax-expressions
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Impertio-Studio/QGIS-Claude-Skill-Package.git /tmp/QGIS-Claude-Skill-Package
mkdir -p .claude/skills
cp -r /tmp/QGIS-Claude-Skill-Package/skills/source/qgis-syntax/qgis-syntax-expressions .claude/skills/qgis-syntax-expressions
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Qgis Syntax Expressions в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Qgis Syntax Expressions, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Qgis Syntax Expressions не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

qgis-syntax-expressions

Quick Reference

Expression Evaluation Pipeline

StepClassPurpose
1. ParseQgsExpression(string)Validate syntax, build AST
2. ContextQgsExpressionContext()Provide variables, fields, scopes
3. ScopesQgsExpressionContextUtilsAdd global/project/layer/feature scopes
4. Evaluateexp.evaluate(context)Execute and return result
5. Validateexp.hasEvalError()Check for runtime errors

Expression Syntax Cheatsheet

ElementSyntaxExample
Field reference"field_name" (double quotes)"population"
String literal'text' (single quotes)'hello world'
Number literal123, 3.1442
NULL checkIS NULL, IS NOT NULL"name" IS NOT NULL
Comparison=, !=, >, >=, <, <="area" > 100
LogicalAND, OR, NOT"pop" > 1000 AND "type" = 'city'
Arithmetic+, -, *, /, ^, %"population" * 1.05
Pattern matchLIKE, ILIKE, ~ (regex)"name" ILIKE '%lake%'
Concatenation||"first" || ' ' || "last"
ConditionalCASE WHEN ... THEN ... ENDCASE WHEN "pop" > 1e6 THEN 'large' ELSE 'small' END
Geometry vars$area, $length, $x, $y$area / 1e6
Current geometry$geometrynum_points($geometry)

Common Expression Functions

CategoryFunctions
Mathsqrt(), abs(), round(), floor(), ceil(), sin(), cos(), pi()
Stringupper(), lower(), length(), trim(), replace(), regexp_replace(), substr(), left(), right()
Conversionto_int(), to_real(), to_string(), to_date(), to_datetime()
Date/Timenow(), day(), month(), year(), hour(), minute(), age(), day_of_week()
Geometry$area, $length, $x, $y, $perimeter, centroid(), buffer(), area(), length(), num_geometries(), num_points()
Aggregatesaggregate(), sum(), count(), mean(), min(), max(), concatenate(), array_agg()
Conditionalsif(), coalesce(), nullif(), try()
Arraysarray(), array_length(), array_contains(), array_append(), array_to_string()
Map/Recordmap(), map_get(), hstore_to_map()
Colorcolor_rgb(), color_hsv(), ramp_color(), darker(), lighter()

Critical Warnings

ALWAYS check exp.hasParserError() after creating a QgsExpression. A parser error means the expression string is syntactically invalid and evaluation will fail silently or return NULL.

ALWAYS check exp.hasEvalError() after calling exp.evaluate(). Evaluation errors occur when the expression is syntactically valid but fails at runtime (e.g., field not found, type mismatch).

ALWAYS set up a proper QgsExpressionContext with appropriate scopes when evaluating expressions that reference fields, project variables, or layer properties. Evaluating without context returns NULL for all field references.

NEVER use double quotes for string literals in expressions. Double quotes reference field names: "name" reads the field, 'name' is the string literal.

NEVER forget to call context.setFeature(feature) before evaluating feature-dependent expressions in a loop. Omitting this causes all features to evaluate against stale or empty data.

NEVER use print() inside custom expression functions (@qgsfunction). Use QgsMessageLog instead. Expression functions run during rendering and print() causes thread-safety issues.

ALWAYS specify referenced_columns in @qgsfunction for performance. Use [QgsFeatureRequest.ALL_ATTRIBUTES] if the function reads arbitrary fields; use [] if it reads no fields.

ALWAYS set usesgeometry=True in @qgsfunction if the function accesses feature.geometry(). Omitting this causes the geometry to be unavailable.


Decision Tree: Choosing the Right Expression Approach

Need to use an expression?
|
+-- Filter features? --> QgsFeatureRequest.setFilterExpression()
|
+-- Calculate field values? --> Field Calculator pattern (edit session + evaluate per feature)
|
+-- Drive labeling? --> QgsPalLayerSettings.fieldName + isExpression = True
|
+-- Drive symbology? --> QgsProperty.fromExpression() on symbol/renderer properties
|
+-- Evaluate standalone? --> QgsExpression.evaluate(context)
|
+-- Need custom logic? --> @qgsfunction decorator + QgsExpression.registerFunction()

Essential Patterns

Pattern 1: Parse and Evaluate an Expression

python
from qgis.core import (
    QgsExpression, QgsExpressionContext, QgsExpressionContextUtils
)

exp = QgsExpression('"population" * 1.05')
if exp.hasParserError():
    raise ValueError(f"Parse error: {exp.parserErrorString()}")

context = QgsExpressionContext()
context.appendScopes(
    QgsExpressionContextUtils.globalProjectLayerScopes(layer)
)

for feature in layer.getFeatures():
    context.setFeature(feature)
    value = exp.evaluate(context)
    if exp.hasEvalError():
        raise ValueError(f"Eval error: {exp.evalErrorString()}")
    print(f"Feature {feature.id()}: {value}")

Pattern 2: Expression-Based Feature Filtering

python
from qgis.core import QgsFeatureRequest

# Method A: expression string directly
request = QgsFeatureRequest().setFilterExpression('"population" >= 50000')
features = list(layer.getFeatures(request))

# Method B: QgsExpression object
exp = QgsExpression('"name" ILIKE \'%lake%\'')
request = QgsFeatureRequest(exp)
features = list(layer.getFeatures(request))

Pattern 3: Field Calculator (Update Attributes)

python
from qgis.core import (
    edit, QgsExpression, QgsExpressionContext,
    QgsExpressionContextUtils
)

exp = QgsExpression('"population" * 2')
context = QgsExpressionContext()
context.appendScopes(
    QgsExpressionContextUtils.globalProjectLayerScopes(layer)
)

with edit(layer):
    for f in layer.getFeatures():
        context.setFeature(f)
        f['doubled_pop'] = exp.evaluate(context)
        layer.updateFeature(f)

Pattern 4: Expression-Based Labeling

python
from qgis.core import QgsPalLayerSettings, QgsVectorLayerSimpleLabeling

settings = QgsPalLayerSettings()
settings.fieldName = '"name" || \' (\' || "population" || \')\''
settings.isExpression = True
settings.enabled = True

text_format = settings.format()
text_format.setSize(12)
settings.setFormat(text_format)

labeling = QgsVectorLayerSimpleLabeling(settings)
layer.setLabeling(labeling)
layer.setLabelsEnabled(True)
layer.triggerRepaint()

Pattern 5: Data-Defined Symbology Properties

python
from qgis.core import QgsProperty

symbol = layer.renderer().symbol()

# Size driven by expression
symbol.setDataDefinedSize(
    QgsProperty.fromExpression('"population" / 1000')
)

# Color driven by expression
symbol.setDataDefinedColor(
    QgsProperty.fromExpression(
        "CASE WHEN \"type\" = 'city' THEN '#ff0000' ELSE '#0000ff' END"
    )
)

layer.triggerRepaint()

Pattern 6: Custom Expression Function

python
from qgis.core import qgsfunction, QgsExpression

@qgsfunction(args='auto', group='Custom', referenced_columns=[])
def population_density(population, area_km2, feature, parent):
    """
    Calculate population density per square kilometer.
    <p>Usage: population_density("pop_field", "area_field")</p>
    """
    if area_km2 and area_km2 > 0:
        return population / area_km2
    return None

# Register (call once, e.g., in plugin initGui)
QgsExpression.registerFunction(population_density)

# Now usable: population_density("population", "area")

# Unregister (call in plugin unload)
QgsExpression.unregisterFunction('population_density')

Context Scope Hierarchy

Scopes are stacked from generic to specific. When variable names collide, the most specific scope wins:

Global scope        → @qgis_version, @user_full_name, custom global vars
  Project scope     → @project_title, @project_crs, custom project vars
    Layer scope     → @layer_name, @layer_id, layer fields
      Feature scope → Feature attributes, $geometry, $id, $currentfeature

Adding Custom Variables

python
from qgis.core import QgsExpressionContextUtils

# Set global variable (persists across sessions)
QgsExpressionContextUtils.setGlobalVariable('my_threshold', 42)

# Set project variable (saved with project)
QgsExpressionContextUtils.setProjectVariable(
    QgsProject.instance(), 'analysis_year', 2024
)

# Set layer variable (saved with layer in project)
QgsExpressionContextUtils.setLayerVariable(layer, 'source_date', '2024-01-15')

# Access in expressions: @my_threshold, @analysis_year, @source_date

Aggregate Expressions

Aggregates compute values across features within a layer:

python
# In expression strings:
# aggregate('layer_name', 'sum', "population")
# aggregate('layer_name', 'mean', "area", filter:="type" = 'residential')

# Common shorthand (current layer):
# sum("population")
# count("id", filter:="active" = 1)
# mean("temperature", group_by:="region")

ALWAYS use the filter parameter in aggregates to limit the scope. Aggregating an entire large layer without a filter is a performance bottleneck.


Reference Links

Official Sources

Файлы в комплекте

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Qgis Syntax Expressions?

Use when writing QGIS expressions for filtering, labeling, symbology, or field calculations. Prevents expression syntax errors and context misconfiguration. Covers QgsExpression parsing, evaluation contexts, field calculator, data-defined properties, and custom functions. Keywords: QgsExpression, expression, field calculator, label expression, data-defined, @qgsfunction, filter, evaluate, calculate field, formula, conditional label, dynamic value.

Зачем использовать Qgis Syntax Expressions в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Qgis Syntax Expressions — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Qgis Syntax Expressions в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/Impertio-Studio/QGIS-Claude-Skill-Package/tree/main/skills/source/qgis-syntax/qgis-syntax-expressions. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Qgis Syntax Expressions?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Qgis Syntax Expressions?

С любым количеством. В TypingMind вы можете использовать Qgis Syntax Expressions с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Qgis Syntax Expressions?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — Impertio-Studio. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇