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ファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 3個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    Impertio-StudioがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Qgis Syntax Expressions」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/Impertio-Studio/QGIS-Claude-Skill-Package/tree/main/skills/source/qgis-syntax/qgis-syntax-expressions
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

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で使用

TypingMindのチャットでQgis Syntax Expressionsを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にQgis Syntax Expressionsを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Qgis Syntax Expressionsは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じ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

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「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.

TypingMindでQgis Syntax Expressionsを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Qgis Syntax Expressionsはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにQgis Syntax Expressionsをインストールするにはどうすればよいですか?

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を使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Qgis Syntax Expressionsで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもQgis Syntax Expressionsを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Qgis Syntax Expressions」は無料ですか?

はい。Impertio-StudioがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇