未分類

q0713がイオン金沢シーサイド店である場合のq0707とq0714の値を0から24の値の数で表示させるSQL文を作成してcsvファイルで保存して下さい。添付したようなグラフを作成するためです。

 

CSVファイルへの保存(psql の場合)

結果をローカルにCSVファイルとして保存するには、以下のコマンドを使用します(1行で記載sにないと、\copy: parse error at end of lineと言われる)

\copy (WITH 時刻範囲 AS (SELECT generate_series(0, 24) AS 時刻) SELECT 時刻範囲.時刻, COALESCE(SUM(CASE WHEN e.q0707 = 時刻範囲.時刻 THEN 1 ELSE 0 END), 0) AS 出発時刻カウント, COALESCE(SUM(CASE WHEN e.q0714 = 時刻範囲.時刻 THEN 1 ELSE 0 END), 0) AS 到着時刻カウント FROM 時刻範囲 LEFT JOIN master_e AS e ON e.q0713 = '京急ストア富岡店' AND e.q0707 BETWEEN 0 AND 24 AND e.q0714 BETWEEN 0 AND 24 GROUP BY 時刻範囲.時刻 ORDER BY 時刻範囲.時刻) TO 'G:/home/ebata/output.csv' WITH CSV HEADER;

イント

  1. Windows環境では絶対パスを使用:
    • G:/home/ebata/output.csv の形式で絶対パスを指定してください。
  2. クエリ結果を手動で確認:
    • 上記SQLを実行後、クエリ結果を確認し、正確なデータが得られることを確認してください。
  3. グラフ作成:
    • このデータを元にPythonやExcelで出発時刻・到着時刻の折れ線グラフを作成できます。

2024,江端さんの忘備録

『提案なんぞいいから、"動くモノ"を持ってこい』

Many customers say, “Forget the proposals, just bring us something that works,”

と、おっしゃるお客さんは多いですが、私は「その言い分はもっともだ」と思っています。

and I think they have a valid point.

イラスト

(↑クリックすると、『10Mのイーサネットのイエローケーブル』と『20年前と完全同一のコントローラーを作って持ってこい』)の話が出てきます)

(↑Click here to see the story of “10M Ethernet yellow cable” and “Make and bring a controller that is the same as it was 20 years ago.”)

-----

私、標準化活動というものに2~3年ほど携わったことがあるのですが、その時実感したのは、―― 『標準化活動とは、先行して自社開発した製品の仕様を、その開発前の会社に押しつける活動』だということです。

I have been involved in standardization activities for a couple of years, and I realized then that “standardization activities are activities to impose the specifications of a product developed by the company ahead of the company on the company that created it before the company.

もちろん、美辞麗句で固めるのであれば、「業界全体の互換性や効率性を高め、顧客にとって利便性を向上させる役割を果たすこと」とかも言えます。

Of course, if we speak in rhetoric, we could also say that it “increases compatibility and efficiency throughout the industry and improves customer convenience.

しかし、ここで重要なのは、『実際に動いているものが、すでにある』という事実なのです。

But what is important here is that 'what is working is already there.

私、以前、標準化活動の団体にドラフトを提出したことがあるのですが、その内容の良し悪しはともあれ、そのドラフトの内容に不安はありませんでした。

I, for one, have submitted a draft to a standards activity organization before, and I had no concerns about the content of that draft, good or bad.

その仕様の通信プロトコルは、実際に私がコーディングして、ちゃんと動いていたからです(実験室レベルで、ですが)。

The reason is that I coded a communication protocol for that specification, and it worked (at the laboratory level, that is).

-----

「検討委員会を立ち上げて」「関係各所の合意を得て」「予算を確保して」「事業計画を精査して」「関連部署と調整して」「リスクアセスメントを実施して」「スケジュールを再調整して」「追加資料を作成して」「専門家の意見を再度取り入れて」「上層部の承認を仰いで」「さらなる意見交換会を開いて」....という場面に、このエンジニア人生において、どれだけ立ち合ってきたことか。

'Establish a study committee,' 'Obtain agreement from all concerned parties,' 'Secure a budget,' 'Scrutinize the business plan,' 'Coordinate with relevant departments,' 'Conduct a risk assessment,' 'Readjust the schedule,' 'Prepare additional materials,' 'Reinvite expert opinions,' 'Seek upper management approval,' and 'Further opinion meeting.” .... I can't tell you how many of these situations I have witnessed in my engineering career.

私は、もうウンザリしているんですよ。

I am sick and tired of it.

多分、お客さんも、同じ気持ちなのではないかと。

Perhaps the customers feel the same way.

-----

そんな中、

In the midst of all that,

『ちなみに、これ、もう動いています』と、だけ言って立ち去る ――

I would say, “By the way, this is already working,” and walk away.

こうして、「声がけ」連中の"メンツ"を潰すのは、エンジニアの醍醐味でもあります。

It is an absolute pleasure for an engineer to crush the “honor” of those who “call the shots” in this way.

詳細については省略します。私、まだ、サラリーマンエンジニアですから。

I'll skip the details. I am still a salaried engineer.

「世界は一人で動かす」

2024,江端さんの忘備録

ChatGPTが凄い奴、ということは、これまで申し上げてきた通りです。

As I have said, ChatGPT is a fantastic thing.

しかし、現在、私が唯一困っているのが「図面の作成」です。

However, the only thing I'm having trouble with now is “drawing up plans.”

私としては、ChatGPTに"線図"を描いて欲しいのですが、こんな図を描いてきます。

I want ChatGPT to draw a “line diagram” for me, but it draws diagrams like this.

『「売国機関」に登場する、チュファルテク合同共和国、クライス連邦、ガルダリケ王国の関係図を、簡単な線図で描いて下さい』とお願いすると、

When I asked them to draw a simple diagram showing the relationships between the Chufartek Union, the Kreis Federation, and the Gardalike Kingdom, which appear in the “Traitorous Organization,”

A simple diagram illustrating the relationships among three fictional countries: Chufartech Union Republic, Kreis Federation, and Gardarike Kingdom. The diagram uses arrows and labels to denote their connections: alliance, rivalry, and trade agreement. Each country is represented by a stylized symbol – a gear for Chufartech, a star for Kreis, and a crown for Gardarike. The background is plain white for clarity.

 

という図が出力されました(内容も間違っています)。

ChatGPT outputs the above figure (the content is also wrong).

ChatGPTと「売国機関」についての会話をした件

-----

仕様書の概要を記載して、線図の作成をお願いしました。

I asked ChatGPT to create a “line diagram” by writing an overview of the specifications.

私が期待していた線図は、こんな感じでした。

This is the kind of diagram I was expecting.

それが、

A detailed schematic diagram of a computer system with a central CPU labeled as '2' in the middle. The CPU is connected with arrows to the following components: Memory (5) for temporary storage, HDD (3) for long-term data storage, Network Interface (6) for external communication, and Monitor Controller (4), which is connected to a Display (7). Additionally, an Input/Output Controller (1) is placed connecting external devices like a keyboard and mouse to the CPU. The diagram shows clear directional arrows representing data flow between components, with a clean and organized layout on a white background.

なんで、こうなる。

Why is that?

 

 

2024,江端さんの忘備録

韓国で戒厳令が施行されたと聞いて、「フェイクニュースにも程がある」と思ったのですが ―― 事実でした。

When I heard that martial law had been declared in South Korea, I thought, “That's taking fake news to the extreme” - but it was true.

戒厳令とは、「国家の非常事態において、軍が特定の地域で行政権や司法権を掌握する法的措置」であり、簡単にいうと、司法と行政が軍によって強制停止させられることです。

Martial law is “a legal measure in which the military seizes administrative and judicial authority in a specific region during a national emergency.” Simply put, the military forcibly suspends the judiciary and administration.

ちなみに、日本国憲法では「戒厳令」は存在しません。

Incidentally, there is no “martial law” in the Japanese constitution.

警察による行動制限がされることはあります(犯罪発生時とか災害時とか)。

There are times when the police will restrict your movements (for example, in the event of a crime or disaster).

また、自衛隊による治安出動もありますが、現行憲法下での治安出動は過去に一度だけありました(八戸市沖でのソ連貨物船暴動(1961年))。あと安保闘争、沖縄復帰運動対応で、治安出動の待機命令がされています。

There have also been instances of the Self-Defense Forces being deployed to maintain public order. Still, there has only been one instance under the current constitution (the Soviet cargo ship riot off the coast of Hachinohe in 1961). In addition, standby orders have been issued to deploy the Self-Defense Forces in response to the Anpo struggle and the movement for the reversion of Okinawa to the Japanese administration.

震災対応の自衛隊の救援活動は、治安出動ではありません(あたりまえだ)。

The Self-Defense Forces' disaster relief activities are not a public security operation (of course).

そもそも日本には「軍隊」が存在しませんので、「軍が特定の地域で行政権や司法権を掌握する法的措置」は論理的に不可能なのです。

To begin with, Japan does not have an army, so it is logically impossible to take “legal measures to have the army seize administrative and judicial authority in a specific region.”

『憲法第9条問題について、考えている人』

実は、コロナ禍の最中に繰り返し発令された「緊急事態宣言」とは、軍の介入のないものの、政府や自治体が主導する市民の行動を制限のことです(但し、法律に基づいて行われます)。

The “state of emergency” declarations repeatedly issued during the coronavirus crisis restrict citizens' behavior led by the government and local governments. However, they do not involve military intervention (the law carries them out).

まあ、「緊急事態宣言」とは、"準戒厳令"とも言えるものではありますが、あの時の、我が国の緊急自体宣言は、コロナ禍の『医療機関の崩壊ギリギリ』を回避した絶妙な発動であったと言えます。

Well, although the “state of emergency declaration” could also be called a “quasi-martial law,” the state of emergency declaration in our country at that time was a finely-tuned declaration that avoided the “collapse of medical institutions” caused by the coronavirus.

私は、『医療機関に辿りつけない人が、死体となって道に放置されている光景』まで想定していたので、あの時の政府の対応は「見事な制御であった」と高く評価しています。

I had imagined a situation where people who couldn't reach medical institutions were left dead on the street, so I highly praise the government's response at the time as “brilliant control.”

(↑クリックでコラムに飛びます)

(Click to go to the column)

話を戻します。

Back to the story.

-----

韓国は当然に軍隊を持っており、憲法にも「戒厳令」の規定があり、それは大統領の専権事項です。

Of course, South Korea has an army, and the constitution also includes a provision for “martial law,” which is the president's sole prerogative.

そもそも、韓国軍は、現時点でも北朝鮮軍と交戦中(休戦しているだけ)です。

To begin with, the South Korean military is still engaged in combat with the North Korean military (they have only suspended hostilities).

韓国大統領は自由意思で戒厳令を発令でき、実際、過去に韓国では何回か戒厳令が発動されました。

The President of South Korea can declare martial law at his discretion, and in fact, martial law has been stated several times in the past in South Korea.

朝鮮戦争(1950年-1953年)と、光州事件(1980年)が、歴史教科書にも掲載されている2大事件ですが、韓国の独裁政権時代(例:李承晩政権、朴正煕政権)には、戒厳令が国内統治に利用されたこともあります。

The two major events included in history textbooks are the Korean War (1950-1953) and the Gwangju Uprising (1980). Still, martial law was also used to govern the country during the era of dictatorship in Korea (e.g., the Lee Seung-man administration and the Park Chung-hee administration).

-----

で、今回の戒厳令ですが ―― 全く訳が分からんです。

And this martial law - I have no idea what it means.

どうやら、独裁政権時代の「国内統治の利用」に近い感じはしますが、凄い違和感を感じます。

It seems similar to the “use of domestic governance” during the dictatorship era, but I feel significant discomfort.

私は、次に韓国で戒厳令が発動されるのは『<北>がソウルに進攻してきた時』と決めつけていたので、この想定外の戒厳令に、本当にビックリしています。

I had assumed that the next time martial law would be declared in South Korea would be 'when the <North> invades Seoul,' so I was surprised by this unexpected declaration of martial law.

まあ、ここ2~3日中に、色々分かってくると思いますので、今はそれを待ちたいと思います。

We'll learn a lot in the next few days, so I'll wait and see what happens.

 

2024,江端さんの忘備録

オーストラリアでは、2024年11月28日に、16歳未満の子どもによるソーシャルメディア(SNS)の利用を禁止する「オンライン安全性改正法案(ソーシャルメディア最低年齢法案)」が議会で可決されました。

In Australia, the Online Safety Amendment Bill (Social Media Minimum Age Bill), which prohibits children under 16 from using social media (SNS), was passed by parliament on November 28, 2024.

この法律は、世界で初めて国家レベルで16歳未満のSNS利用を禁止するものです。

This law is the first in the world to ban social networking services by people under 16 nationally.

―― と、ここまでは知っていたのですが、もう少し調べてみました。

I knew this much, but I did some more research.

■ X(旧Twitter)、TikTok、Instagram、Facebook、Snapchatなどの主要SNSが含まれる。一方、YouTubeやメッセージングアプリ、教育・健康支援を主目的とするサービス(例:Google Classroom、Headspace、Kids Helpline)は適用対象外

This includes primary social networking services such as X (formerly Twitter), TikTok, Instagram, Facebook, and Snapchat. On the other hand, YouTube, messaging apps, and services whose primary purpose is to provide educational or health support (e.g., Google Classroom, Headspace, Kids Helpline) are not covered.

■SNS運営企業は、16歳未満のユーザーがアカウントを作成・利用できないよう合理的な措置を講じる必要がある。違反した場合、最大約50億円の罰金が課せられる。

SNS management companies must take reasonable measures to prevent users under 16 from creating or using accounts. If they are found to be in breach of this, they could be fined up to 5 billion yen.

■ユーザーに公式な身分証明書の提出を強制することはできないので、運営企業は代替手段を提供することが求めらる。年齢確認のために収集したデータは適切に破棄しなければならず、違反時には同様の罰金が科せられる。

Since it is impossible to force users to submit official identification, the operating company must provide an alternative method. The data collected for age verification must be appropriately destroyed, and the same fine will be imposed in case of a violation.

-----

さて、この法律の立法根拠は、ざっくり以下の4点のようです。

The legislative basis for this law seems to be roughly as follows.

(1)60%以上の子どもが視聴しているという、薬物乱用、自殺、自傷行為、暴力的な内容などの極めて有害なコンテンツからの保護

(1) Protection from extremely harmful content such as drug abuse, suicide, self-injury, and violent content, which is viewed by over 60% of children.

(2)SNSを通じた、いじめや性的被害の防止

(2) Prevention of bullying and sexual abuse through social networking services

(3)若者の不安や抑うつ、摂食障害などの問題などのメンタルへの影響の軽減

(3) Reducing the impact on mental health, such as anxiety, depression, and eating disorders, among young people

(4)(政府の調査で)95%の保護者からの要望

(4) (According to a government survey) 95% of parents requested

翻訳文が見つからなかったので、原文サーチしてみたのですが、これは補正案だけようです ―― まあ、そのうち、翻訳版も手に入るでしょう(原文のURLご存知の方は教えて下さい)。

I couldn't find a translation, so I tried searching for the original text, but it seems that this is just a draft of the corrections - well, I'm sure we'll get a translation version eventually (if you know the URL of the original text, please let me know)

-----

私の最初の感想は『ブログはOKなんだ』でした。

My first thought was, “Blogging is OK.

私は、SNSはアカウントを持っていますが、稼動していない状態です(家族と大学の業務と帰宅連絡用にLINEのアカウントは持っていますが、使い方は「メールの替わり」です)。

I have an account on a social networking service, but it's not active (I have a LINE account for use with my family, university work, and to let people know when I've arrived home, but I use it as a “substitute for email”).

私、青少年の自殺者数の増加は、SNSとの関連があると疑っていますので、オーストラリアのこの法律によって、あの国で何が変わるのかを、注意深く観察したいと思っています。

I suspect that the increase in the number of youth suicides is related to social networking services, so I want to carefully observe what changes will occur in that country as a result of this law in Australia.

小中高生の自殺者数500人超と高止まり 厚生労働省「危機的な状況」として対策を強化

-----

オーストラリアという国は、結構アバンギャルドでラディカルな法律を作るので、私、結構「楽しく」観察しております。

The country of Australia makes quite avant-garde and radical laws, so I am pretty enjoying observing them.

あの国の法律は、飲酒や喫煙ついてはもちろん、労働時間外の「通信拒絶権」など、世界に先駆けていると思います。

I think that the laws of that country are leading the world, not only in terms of drinking and smoking but also in terms of things like the right to refuse communication outside of working hours.

また、オーストラリアでは、「イカや魚の活き造りが法律違反」というのを聞いた時にも驚きました。

Also, in Australia, I was surprised to hear that it was against the law to serve sashimi of squid or fish.

しかし、ちょっと調べたところ、似たような法律、色々な国でも見つかりました。

However, after researching, I found similar laws in various countries.

■オーストラリアでは2017年、ロブスターを生きたまま解体していたレストランが有罪判決を受けた。

In Australia, in 2017, a restaurant that was caught dismembering live lobsters was convicted.

■スイスでは2018年に動物保護規定が見直され、甲殻類を生きたまま熱湯で茹でる調理法が禁止された。

In Switzerland, animal protection regulations were revised in 2018, and the cooking method of boiling crustaceans alive in boiling water was banned.

■イギリスでは2021年に甲殻類や軟体動物にも苦痛を感じる知覚があるとする報告書がまとめられ、これらの動物が動物福祉の保護対象に加えられた。

In the UK, a report was compiled in 2021 that stated that crustaceans and mollusks also could feel pain, and these animals were added to the list of animals protected by animal welfare laws.

日本人から見れば、これらの法律は『ふーん』と思う程度かもしれませんが、彼らから見ると、日本人は『野蛮な民族』と見られている可能性はあります。

From the Japanese perspective, these laws may seem like a minor inconvenience, but from their perspective, there is a possibility that the Japanese are seen as a 'savage people.'

ってまあ、そんなことは、これまでの反捕鯨団体の活動を見れば、明らかですね。

Well, that much is clear from looking at the activities of anti-whaling groups to date.

-----

中国では、客人に自らの肉を提供するという文化的慣習が存在したとされています。特に、親孝行の一環として、病気の親に自分の肉を切り取って食べさせる行為が美徳とされることがありました(宋の時代以降に広まったとされている)。

In China, there is a cultural custom of offering your flesh to guests. In particular, as part of being a dutiful child, it was considered virtuous to cut off a piece of your flesh and feed it to your sick parents (this custom is said to have become widespread after the Song Dynasty).

三国志の時代には、劉安という人物が劉備に自分の妻の肉を料理して振る舞ったという逸話があります。

There is a story from the Three Kingdoms period about a man named Liu An who served his wife's flesh to Liu Bei.

-----

私、異文化理解とは、その国にあっては、その国の文化を尊重することだと思うのです。

I think that intercultural understanding means respecting the culture of the country you are in.

ですから、仮に、私がどこかの国で、切り取った人間の肉で饗応されたとしても『ちゃんと食べ切る』自信があります。

So, even if I were to be entertained with cut-up human flesh in some country, I'm confident that I could eat it all up.

ましてや、犬、ネズミ、モルモット、クモ、ワニ、昆虫なんぞ、完全にO.K.です(味が悪ければ食べませんが)。

And, of course, dogs, mice, guinea pigs, spiders, crocodiles, insects, etc., are OK (I won't eat them if they don't taste good).

ちなみに、カニバリズムが忌避されるようになったのは、比較的最近です(キリスト教の台頭後、世界的には16~19世紀))。

Incidentally, cannibalism only became taboo relatively recently (in the 16th to 19th centuries worldwide, after the rise of Christianity).

2024,江端さんの忘備録

「上司に自分の成果を取られた」という話はよく聞きますが、私はあまり経験したことがありません(私が鈍感で気がついていないだけかもしれませんが)。

I often hear people say that their boss took credit for their work, but I've never really experienced it myself (although I may be insensitive and not realize it).

エンジニア(技術者)の成果は、大抵、エンジニア本人でなければ活用することができません ―― 逆に言うと、他人の開発した技術は、自分にとっては「呪文」のようなものです。

The results of engineers (technicians) can usually only be utilized by the engineers themselves - in other words, technology developed by others is like a “spell” to you.

またエンジニアが執筆した特許明細書も、エンジニア本人でなければ、補正や修正の対応ができません。発明に関して言えば、自分で執筆した発明ですら、1年後には、自分で読んでも分からない「呪文」になっているくらいです。

Also, you cannot make corrections or amendments if you are not the engineer who wrote the patent specification. When it comes to inventions, even if you wrote the invention yourself, a year later, it will be like a “spell” that you won't understand even if you read it yourself.

つまりですね、技術というのは、属人性が高く、他人への譲渡が恐しく困難なのです ―― 技術分野や技術内容にも因るとは思いますが

In other words, technology is highly personalized, and it is tough to transfer to other people. I think this depends on the field and content of the technology.

ご存知の通り、私は自分の技術(のようなもの)のメモをばら撒いているのですが、全く継承されている感じがしません。

As you know, I'm scattering notes about my skills (or something like that), but I don't feel like they're being passed on.

-----

エンジニアって『上司に成果を取られた』と嘆く場面が、他の業種ほどは多くない ―― と、断言できるかどうかは自信はないのですが、上司や他の人に、ラクチンにその『成果』を理解してもらえるなら、私は嬉しい。凄く嬉しい。

I'm unsure if I can confidently say that engineers don't have as many occasions to lament to their superiors about the results they've achieved as people in other industries. Still, I'd be happy if my superiors and other people could easily understand the results I've achieved. I'd be satisfied.

私としては、「理解して貰えるなら、成果であれ、何であれ、『もってけドロボー』という気持ちになることが多いです。

If I can get my point across, I often feel like saying, “Take it, thief!” whether it's about the result or something else.

技術に携わる人間の一人としては、「特許出願」も「学会発表」も「論文発表」も、面倒くさ過ぎると思っています。

 

2017,江端さんの忘備録

(昨日の続きです)

(Continuation from yesterday)

作成途中の、機能の一部だけを実装した、

I ask the engineers to open a part of the source code that realizes a part of the whole function. In addition, the code might be

■汚くて、

lame, unmade

そして

and

■ステップ数が短い(どんなに長くも100行)

shorter (less than 100 steps, if ever)

コードを、バシバシ公開して頂きたいのです。

I want to read such incomplete codes.

そのようなプログラムは、大抵の場合、アルゴリズムの「根っこ」であったりします。

Those codes are, in many cases, fundamental functions of the algorithm.

そして、その「根っこ」は、私にとっては、完成した完璧なソースコードより、はるかに価値があるのです。

For me, the code is far better than the complete source code.

汚いコードは、データ構造の本質を理解するのに、大変助かりますし、

A lame and unmade code helps understand a basic structure of data and

短いコードは、そのアルゴリズムを理解するのに、大変助かります。

A shorter code is beneficial for understanding the basic algorithm.

特に、実時間処理を施しているコードなどにおいては、その処理を施す前のコードが、私にとっては至宝のコードです。

Especially about a code that implements a real-time processing function, the old code, before implementing the process, is extraordinarily fine for me.

(実時間処理が入ってくると、トレースができないから)

It will not be accessible if the real-time process includes the code traces.

-----

善意でソースコードを公開して頂いている方の多くは、ソースコードを作ることが大好きで、

Many engineers, who have opened their source code with good-will, love to make codes,

そして、

however,

―― ドキュメント(解説資料)を作るのが大嫌い

they don't like write a document(like instruction manual,practical guide)

です。

もし、その方から、「ソースコード自体が、ドキュメントそのものだろう」と言われると、それはもっともな話で、グウの根も出ません。

If they say, "source code itself is a manual" to me, I don't argue against them.

それが、正論だからです。

Because it is a just argument.

なにより、自分のソースコードを公開している私自身も、ドキュメントは作っていません。

Above all, I also posted my source code on the Internet, but I have not made the manual since.

-----

だから、「ドキュメントを書いて下さい」とは言いませんので、

So I don't say "Please write "readme.txt" down". but I want to say to them

「作成プロセス途中の、小さくて、汚いソースコードを残して下さい」

"Please leave your lame, unmade, and shortcode under construction."

と申し上げさせて頂いている次第なのです。

With the most excellent courtesy.

2024,江端さんの技術メモ

改めてGeoEntityDBの作り方の手順を示して下さい。

 

以下に、GeoEntityDB を作成する手順を改めて示します。


GeoEntityDBの作成手順

1. GeoEntityDBの作成

  1. PostgreSQLに接続します。
    psql -U postgres

     

  2. 新しいデータベースを作成し、PostGISを有効化します。
    CREATE DATABASE GeoEntityDB; \c GeoEntityDB CREATE EXTENSION postgis; CREATE EXTENSION pgrouting; -- 必要に応じて有効化

     


2. 地物テーブルの作成

地物データを格納するためのテーブルを作成します。

  1. テーブルスキーマを定義します。以下はカテゴリ付きの地物データ用のスキーマです。
    CREATE TABLE geo_entities ( id SERIAL PRIMARY KEY, -- 自動生成の一意識別子 category VARCHAR(10), -- カテゴリ (例: A1, B1, D2) stay_time INTEGER, -- 滞在時間 (分) geom GEOMETRY(POINT, 4326) -- 座標データ (EPSG:4326の緯度経度) );

    # id SERIAL PRIMARY KEY の部分は自動的にインポートされるので、csvの先頭の番号は行削除しておくこと

  2. インデックスを作成して検索性能を向上させます。
    CREATE INDEX geo_entities_geom_idx ON geo_entities USING GIST (geom);

     


3. CSVデータのインポート

CSVファイルから地物データをインポートします。

  1. 一時テーブルを作成(緯度・経度データを変換するために使用)。
    CREATE TEMP TABLE temp_geo_entities ( category VARCHAR(10), stay_time INTEGER, latitude DOUBLE PRECISION, longitude DOUBLE PRECISION );

     

  2. CSVをインポート(ファイルのパスは実際のCSVファイルの場所を指定してください)。
    COPY temp_geo_entities (category, stay_time, latitude, longitude) FROM '/path/to/geo_entities.csv' DELIMITER ',' CSV HEADER;

    # 実は、'/path/to/geo_entities.csv'の部分で酷く転けた記憶があるが、結果的にインポートできてしまったので、忘れた。

  3. 本テーブルに挿入(緯度・経度を POINT 型に変換して挿入)。
    INSERT INTO geo_entities (category, stay_time, geom) SELECT category, stay_time, ST_SetSRID(ST_MakePoint(longitude, latitude), 4326) FROM temp_geo_entities;

     

  4. データが正しくインポートされたか確認します。
    SELECT * FROM geo_entities LIMIT 10;

    #ここから先は試していないが、メモに残しておく。


4. 既存DBとの連携設定

方法 1: postgres_fdw を使った連携

hakata_ex_cost_db(道路ネットワークDB)と GeoEntityDB を連携させます。

  1. postgres_fdw を有効化(GeoEntityDBで実行)。
    CREATE EXTENSION postgres_fdw;

     

  2. 外部サーバーを登録
    CREATE SERVER hakata_server FOREIGN DATA WRAPPER postgres_fdw OPTIONS (dbname 'hakata_ex_cost_db', host 'localhost');

     

  3. 外部DBへのユーザーマッピングを作成
    CREATE USER MAPPING FOR current_user SERVER hakata_server OPTIONS (user 'postgres', password 'your_password');

     

  4. 必要なテーブルをインポート(例: 道路ネットワークテーブル)。
    IMPORT FOREIGN SCHEMA public FROM SERVER hakata_server INTO public;

     

  5. テーブルが使用可能か確認
    SELECT * FROM ways LIMIT 10;

     


5. 経路計算の設定

最短経路計算の基本例

エージェントの現在地から目的地(地物)までの経路を計算します。

  1. エージェントの現在地に最も近いノードを取得
    SELECT id FROM ways_vertices_pgr ORDER BY geom <-> ST_SetSRID(ST_MakePoint(130.3980676, 33.59543503), 4326) LIMIT 1;

     

  2. 地物の位置に最も近いノードを取得
    SELECT id FROM ways_vertices_pgr ORDER BY geom <-> (SELECT geom FROM geo_entities WHERE id = 1) LIMIT 1;

     

  3. Dijkstraアルゴリズムで経路計算
    SELECT seq, id1 AS node, id2 AS edge, cost FROM pgr_dijkstra( 'SELECT id, source, target, cost FROM ways', start_node_id, end_node_id, directed := false );

     


6. 地物データと経路計算の組み合わせ

以下のようなクエリで、地物データの位置と経路計算を連携させます。

  1. エージェントの現在地から15メートル以内の地物を検索(これ、上手く稼動しません。下の方は使って下さい)
    SELECT id, category, stay_time, ST_Distance(geom, ST_SetSRID(ST_MakePoint(130.3980676, 33.59543503), 4326)) AS distance FROM geo_entities WHERE ST_DWithin(geom, ST_SetSRID(ST_MakePoint(130.3980676, 33.59543503), 4326), 15);

     

  2. 発見した地物への最短経路を計算
    SELECT seq, id1 AS node, id2 AS edge, cost FROM pgr_dijkstra( 'SELECT id, source, target, cost FROM ways', start_node_id, (SELECT id FROM ways_vertices_pgr ORDER BY geom <-> (SELECT geom FROM geo_entities WHERE id = found_geo_id) LIMIT 1), directed := false );

     


まとめ

  1. GeoEntityDBの作成とデータインポート:
    • PostGISとpgRoutingを有効化し、CSVデータを地物テーブルに格納。
  2. 既存DBとの連携:
    • postgres_fdw を使用して、hakata_ex_cost_db の道路ネットワークを参照。
  3. 経路計算の実装:
    • エージェントの現在地と地物データを連携させ、道路ネットワーク上で最短経路を計算。

これにより、エージェントが嗜好に応じて地物に向かう動きをリアルにシミュレーションする仕組みを構築できます。

ーーーーー
こういうミスもやったので、以下のメモに残しておく。

SELECT * FROM geo_entities WHERE category = 'B1'; としたらエントリーがでてきませんが、
SELECT * FROM geo_entities WHERE category = ' B1'; としたらエントリーがでてきました。
categoryの要素でえ最初に空白が入っているものを修正したいのですが、どうしたら良いでしょうか

 

category の要素の先頭に空白が含まれている場合、それを修正するには TRIM 関数を使用して先頭と末尾の空白を取り除く必要があります。以下に、データを修正する方法を説明します。


手順

1. データの確認

まず、空白が含まれているデータを確認します。

SELECT * FROM geo_entities WHERE category LIKE ' %' OR category LIKE '% ';

 

  • LIKE ' %' は先頭に空白があるデータを検索します。
  • LIKE '% ' は末尾に空白があるデータを検索します。

2. 空白を修正

TRIM 関数を使用して、category カラムから空白を取り除きます。

すべてのエントリを修正する場合

以下のクエリで、空白を削除した値に更新します。

UPDATE geo_entities SET category = TRIM(category) WHERE category LIKE ' %' OR category LIKE '% ';

 


3. 修正結果の確認

修正後に、データが正しく更新されたか確認します。

SELECT * FROM geo_entities WHERE category LIKE ' %' OR category LIKE '% ';

 

  • クエリの結果が空であれば、すべての空白が正常に削除されたことを意味します。

4. 再度クエリを実行

修正後、以下のようにクエリを実行して正しいデータが取得できるか確認します。

SELECT * FROM geo_entities WHERE category = 'B1';

 


補足

  • TRIM の動作: TRIM 関数は、先頭と末尾の両方から空白を削除します(不要なスペースも含む)。
  • データの一時バックアップ: データ更新は破壊的変更となるため、念のため更新前にバックアップを取得しておくことをおすすめします。

これで問題が解決するはずです!もしさらなるサポートが必要であればお知らせください。


ざっくりとした使い方

 

geoentitydb=# \l
List of databases
Name | Owner | Encoding | Locale Provider | Collate | Ctype | ICU Locale | ICU Rules | Access privileges
--------------------+----------+----------+-----------------+------------+------------+------------+-----------+-----------------------
geoentitydb | postgres | UTF8 | libc | en_US.utf8 | en_US.utf8 | | |
hakata_db | postgres | UTF8 | libc | en_US.utf8 | en_US.utf8 | | |
hakata_ex_cost_db | postgres | UTF8 | libc | en_US.utf8 | en_US.utf8 | | |

geoentitydb=# SELECT id, category, stay_time, geom FROM geo_entities where id = 29;
id | category | stay_time | geom
----+----------+-----------+----------------------------------------------------
29 | B1 | 20 | 0101000020E610000006802A6E9C4C6040099FB5F44BCB4040

 

geoentitydb=# SELECT id, category, stay_time, ST_X(geom) AS longitude, ST_Y(geom) AS latitude FROM geo_entities where id = 29;
id | category | stay_time | longitude | latitude
----+----------+-----------+-------------+-------------
29 | B1 | 20 | 130.3940955 | 33.58825549

こんな感じででてくる。

以下は、130.4064827799044, 33.591348965846656 から 100メートル以内のジオエンティティを抽出するSQLです。(こっちが正しい)

geoentitydb=# SELECT id, category, stay_time, ST_Distance(geom::geography, ST_SetSRID(ST_MakePoint(130.4064827799044, 33.591348965846656), 4326)::geography) AS distance FROM geo_entities WHERE ST_DWithin(geom::geography, ST_SetSRID(ST_MakePoint(130.4064827799044, 33.591348965846656), 4326)::geography, 100);

id | category | stay_time | distance
------+----------+-----------+-------------
304 | A2 | 60 | 68.03775787
357 | A3 | 120 | 75.80618279
366 | A3 | 120 | 76.48825161
414 | D2 | 180 | 80.65210758
415 | D2 | 180 | 79.93815148
429 | D2 | 180 | 61.23626794
435 | D2 | 180 | 62.50441807
546 | E1 | 480 | 77.36793898
550 | E1 | 480 | 90.09868468
813 | E2 | 300 | 54.40053345
1174 | F2 | 10 | 92.85196166
1217 | F2 | 10 | 89.44133931
1933 | H2 | 30 | 64.5772006
1942 | H2 | 30 | 84.70916514
(14 rows)

2024,江端さんの忘備録

このブログは、私のメモです。ですので、何でも書き込みます。

This blog is my notebook, so I write about anything.

週末は、大学の研究やコーディングで終日狂っていますので、技術メモも増えます。

On weekends, I spend all day doing university research and coding, so I also end up with more technical memos.

で、この技術メモの内容が理解できる人は、非常に少ないと思っています。

I think very few people can understand the contents of this technical memo.

なにしろ、動機や背景、そして、DBのスキーマについても一切記載がないのですから、ここから読み取れる人がいたら、その人は「天才以上」といっても良いでしょう。

After all, the motives, background, and database schema are not mentioned, so if anyone can read this, they must be “more than a genius.”

『実際のところ、江端は技術漏洩しているんじゃないか?』と疑っている人がいるかもしれませんが、私が公開している情報は、基本的に公開されている情報を、私のためだけに二次加工して公開しているものですので、技術漏洩には当たりません ―― というか、この点については、私は常に細心の注意を払っています。

There may be people who suspect that “Ebata is leaking technology.” Still, the information I am releasing is publicly available and reprocessed for my use, so it does not constitute a technology leak. I am always cautious about this.

忘れないでください ―― 私は「会社の犬」です。

ただ、私のページを読んで頂いている方の多くに、「読み難い思いをさせているだろう」という予想はつきます。

However, I can imagine that many people reading my page have difficulty reading it.

多分、全然興味がなく、膨大な内容で、かつ意味不明な内容でしょう。

They are probably not attractive, and a vast amount of content makes no sense.

では、なぜ私が、このような意味不明な技術メモを開示し続けているかというと、自分自身の業務や大学での研究などで、便利なんですよ。

The reason I continue to disclose these incomprehensible technical memos is that they are helpful for my work and research at the university.

まず 、『私は、過去の失敗を簡単に忘れる。なので、直ぐにメモを取る。そのメモは私に分かれば十分であり、他人に理解してもらう必要がない』ことが挙げられます。

First of all, “I easily forget past mistakes. So, I take notes immediately. Those notes are sufficient for me to understand, so others do not need to understand them.”

ならば、『そのメモは非公開にして江端だけ見れるようにすれば良い』とも言えます。

Then, you could say, 'Make the memo private so that only Ebata can see it.

ところが、『私がハマった部分』が、私以外の人に役にたっている可能性があるのです。

However, there is a possibility that the part that I was stuck on is useful for other people.

たとえば、本日のメモですと、

For example, today's memo is

q0713がイオン金沢シーサイド店である場合のq0707とq0714の値を0から24の値の数で表示させるSQL文を作成してcsvファイルで保存して下さい。添付したようなグラフを作成するためです。

実際に、SQL文でのCSVファイルの保存に失敗する人に、稼動実績のあるコマンドを、丸ごと提供できます。

I can provide a command that has been proven to work for people who are having trouble saving CSV files in SQL statements.

これは、他のエンジニアにとっても助かるはずなのです ―― なぜ、そう言い切れるか? 「私が、他の人のメモで助けられてきたから」です。

This will also be helpful for other engineers - why can I say that? Because other people's notes have helped me.

「作成プロセス途中の、小さくて、汚いソースコードを残して下さい」

という訳で、私のページを読んで頂いている方には、迷惑をおかけしているとは思いますが、当面、この運用を続けてまいります。

So, I apologize to those of you who are reading my page for any inconvenience caused, but for now, I will continue to operate it in this way.

悪しからずご了承下さい。

Please accept my apologies.

未分類

select household, q0301 from master_b where household like 'P%'; で、(Pで始まる)ユーザ番号と、ユーザの年齢が出てきます。 select household, q0707,q0714 from master_e; で、(Pで始まる)ユーザ番号と、出発時刻(0-24)、と到着時刻(0-24)が出てきます。 この2つのSQL文をくみあわせて、0-9歳、10ー19歳、 ..... 90-99歳に分類して、それぞれの年齢分類毎の出発時刻と到着時刻を算出するSQL文を作って下さい。

以下は、出発時刻 (q0707) と到着時刻 (q0714) の 標準偏差 を算出する SQL 文です。標準偏差は STDDEV 関数を使用して計算します。

SELECT 
    CASE 
        WHEN b.q0301 BETWEEN 0 AND 9 THEN '0-9歳'
        WHEN b.q0301 BETWEEN 10 AND 19 THEN '10-19歳'
        WHEN b.q0301 BETWEEN 20 AND 29 THEN '20-29歳'
        WHEN b.q0301 BETWEEN 30 AND 39 THEN '30-39歳'
        WHEN b.q0301 BETWEEN 40 AND 49 THEN '40-49歳'
        WHEN b.q0301 BETWEEN 50 AND 59 THEN '50-59歳'
        WHEN b.q0301 BETWEEN 60 AND 69 THEN '60-69歳'
        WHEN b.q0301 BETWEEN 70 AND 79 THEN '70-79歳'
        WHEN b.q0301 BETWEEN 80 AND 89 THEN '80-89歳'
        WHEN b.q0301 BETWEEN 90 AND 99 THEN '90-99歳'
        ELSE 'その他'
    END AS 年齢分類,
    AVG(e.q0707) AS 平均出発時刻,
    STDDEV(e.q0707) AS 出発時刻の標準偏差,
    AVG(e.q0714) AS 平均到着時刻,
    STDDEV(e.q0714) AS 到着時刻の標準偏差
FROM 
    master_b AS b
JOIN 
    master_e AS e
ON 
    b.household = e.household
WHERE 
    b.household LIKE 'P%'
    AND e.q0707 <> 999
    AND e.q0714 <> 999
GROUP BY 
    年齢分類
ORDER BY 
    年齢分類;

修正点:

  1. 標準偏差の計算:
    • STDDEV(e.q0707) AS 出発時刻の標準偏差
    • STDDEV(e.q0714) AS 到着時刻の標準偏差
    • 標準偏差を計算するために、STDDEV 関数を使用。
  2. 出力項目:
    • 年齢分類
    • 平均出発時刻
    • 出発時刻の標準偏差
    • 平均到着時刻
    • 到着時刻の標準偏差

出力例:

pj20005=# \e
 年齢分類 |    平均出発時刻     | 出発時刻の標準偏差 |    平均到着時刻     | 到着時刻の標準偏差
----------+---------------------+--------------------+---------------------+--------------------
 0-9歳    |  8.7364864864864865 | 2.0264293870576348 | 16.6959459459459459 | 2.7902629433767539
 10-19歳  |  8.6916488222698073 | 2.3823202999576382 | 17.5610278372591006 | 3.1068884868890622
 20-29歳  |  8.9774436090225564 | 2.7632636644010746 | 17.8020050125313283 | 3.7370800926049844
 30-39歳  |  9.0335731414868106 | 2.3690328974486025 | 17.1534772182254197 | 2.9668749279360904
 40-49歳  |  9.0164835164835165 | 2.4084051553191729 | 16.9326923076923077 | 3.3338216665822259
 50-59歳  |  9.1076555023923445 | 2.7224076287670418 | 17.6854066985645933 | 3.2784704658907816
 60-69歳  |  9.7626321974148061 | 2.8109242893099341 | 16.5687426556991774 | 3.1044389062381429
 70-79歳  | 10.4559659090909091 | 2.5466884006062182 | 15.2897727272727273 | 3.0459374095847468
 80-89歳  | 10.4758454106280193 | 2.4712413371273877 | 15.1835748792270531 | 2.9226415927228037
 90-99歳  | 10.0217391304347826 | 2.7260261951824853 | 15.1086956521739130 | 3.3890099517874430
 その他   |  8.9574468085106383 | 2.7431827273506346 | 16.6170212765957447 | 3.1146769555086844