STEM 隨筆︰古典力學︰模擬術【可視化】 B

天下事分分合合,往往各以其理!

搭配起來常常多處不適,於是煩惱生耶?

如今那

/pydy-viz

pydy-viz

Notice

pydy-viz has been merged into the main pydy repository. This independent project is now deprecated, all development and subsequent releases will be from http://github.com/pydy/pydy.

Visualization of multibody systems generated with PyDy.

 

已經合併!

恰巧正逢這

/ipywidgets

Interactive widgets for the Jupyter Notebook https://ipywidgets.readthedocs.io

ipywidgets: Interactive HTML Widgets

Version Build Status Documentation Status Join the chat at https://gitter.im/ipython/ipywidgets

ipywidgets are interactive HTML widgets for Jupyter notebooks and the IPython kernel.

Notebooks come alive when interactive widgets are used. Users gain control of their data and can visualize changes in the data.

Learning becomes an immersive, plus fun, experience. Researchers can easily see how changing inputs to a model impact the results. We hope you will add ipywidgets to your notebooks, and we’re here to help you get started.

Core Interactive Widgets

A demonstration notebook provides an overview of the core interactive widgets, including:

  • sliders
  • progress bars
  • text boxes
  • toggle buttons and checkboxes
  • display areas
  • and more

Jupyter Interactive Widgets as a Framework

Besides the widgets already provided with the library, the framework can be extended with custom widget libraries.

A template project is available in the form of a cookie cutter here.

This project is meant to help custom widget authors get started with the packaging and the distribution of Jupyter interactive widgets.

It produces a project for a Jupyter interactive widget library following the current best practices for using interactive widgets. An implementation for a placeholder “Hello World” widget is provided.

Popular widget libraries such as bqplot, pythreejs and ipyleaflet

follow exactly the same template and directory structure. They can serve as more advanced examples of usage of the Jupyter widget infrastructure.

For detailed information, please refer to the ipywidgets documentation.

 

早定分殊?

此所以整合過程憂報不斷乎?!

‧ Not working across all browsers and OSs #113

‧ ipywidgets 5.0 has been released and is backwards incompatible #348

……

 

莫說沒有熱忱者開道來告知︰

You can modify the cell like this until a fix has been merged:

scene.display_ipython()
import IPython.display
IPython.display.display(IPython.display.HTML(scene._html_widget.value))

 

方不方便,宜且不宜,端賴用者矣!?

 

※ 註︰版本還請與 『原範例網頁』比較︰

 

※ 註︰ 最好放在最後一格。

 

※ 註︰須先安裝 IPython 之

 Use the ‘%version_information’ IPython magic extension in a notebook to display information about which versions of dependency package that was used to run the notebook.

Installation

 Install the version_information package using pip:
pip install version_information

……

/version_information

IPython magic command for showing version information for dependency modules in a notebook.

哩。

 

 

 

 

 

 

 

STEM 隨筆︰古典力學︰模擬術【可視化】 A

絕句‧杜甫

兩個黄鸝鳴翠柳,
一行白鷺上青天。
窗含西嶺千秋雪,
門泊東吳萬里船。

詩聖杜甫七言絕句有四首

堂西長筍别開門,塹北行椒卻背村。
梅熟許同朱老吃,松高擬對阮生論。

欲作魚梁雲複湍,因驚四月雨聲寒。
青溪先有蛟龍窟,竹石如山不敢安。

兩個黄鸝鳴翠柳,一行白鷺上青天。
窗含西嶺千秋雪,門泊東吳萬里船。

藥條藥甲潤青青,色過棕亭入草亭。
苗滿空山慚取譽,根居隙地怯成形。

,何必特舉其三說?難悟實相金剛義!娑婆世界有情多,純量造化色菩提☆★

……

不空強空成頑空,空空不空有時盡,

一念大悲觀自在,人間哪處非紅塵!!??

─── 《GOPIGO 小汽車︰格點圖像算術《彩色世界》詩說

 

也曾因著所謂『一圖勝千言』,

樂觀的想,視覺闡釋周遭環境,潛意識補足推理所需,

Visual perception is the ability to interpret the surrounding environment by processing information that is contained in visible light. The resulting perception is also known as eyesight, sight, or vision (adjectival form: visual, optical, or ocular). The various physiological components involved in vision are referred to collectively as the visual system, and are the focus of much research in psychology, cognitive science, neuroscience, and molecular biology, collectively referred to as vision science.

Leonardo da Vinci (1452–1519) is believed to be the first to recognize the special optical qualities of the eye. He wrote “The function of the human eye … was described by a large number of authors in a certain way. But I found it to be completely different.” His main experimental finding was that there is only a distinct and clear vision at the line of sight—the optical line that ends at the fovea. Although he did not use these words literally he actually is the father of the modern distinction between foveal and peripheral vision.[citation needed]

220px-Eye_Line_of_sight

Leonardo da Vinci: The eye has a central line and everything that reaches the eye through this central line can be seen distinctly.

Fovea centralis

The fovea centralis (the term fovea comes from the Latin, meaning pit or pitfall) is a small, central pit composed of closely packed cones in the eye. It is located in the center of the macula lutea of the retina.[1][2]

The fovea is responsible for sharp central vision (also called foveal vision), which is necessary in humans for activities where visual detail is of primary importance, such as reading and driving. The fovea is surrounded by the parafovea belt, and the perifovea outer region.[2] The parafovea is the intermediate belt, where the ganglion cell layer is composed of more than five rows of cells, as well as the highest density of cones; the perifovea is the outermost region where the ganglion cell layer contains two to four rows of cells, and is where visual acuity is below the optimum. The perifovea contains an even more diminished density of cones, having 12 per 100 micrometres versus 50 per 100 micrometres in the most central fovea. This, in turn, is surrounded by a larger peripheral area that delivers highly compressed information of low resolution following the pattern of compression in foveated imaging.

Approximately half of the nerve fibers in the optic nerve carry information from the fovea, while the remaining half carry information from the rest of the retina. The parafovea extends to a radius of 1.25 mm from the central fovea, and the perifovea is found at a 2.75 mm radius from the fovea centralis.[3]

Schematic_diagram_of_the_human_eye_en.svg

Schematic diagram of the human eye, with the fovea at the bottom. It shows a horizontal section through the right eye.

Unconscious inference

Main article: Unconscious inference

Hermann von Helmholtz is often credited with the first study of visual perception in modern times. Helmholtz examined the human eye and concluded that it was, optically, rather poor. The poor-quality information gathered via the eye seemed to him to make vision impossible. He therefore concluded that vision could only be the result of some form of unconscious inferences: a matter of making assumptions and conclusions from incomplete data, based on previous experiences.[citation needed]

Inference requires prior experience of the world.

Examples of well-known assumptions, based on visual experience, are:

  • light comes from above
  • objects are normally not viewed from below
  • faces are seen (and recognized) upright.[6]
  • closer objects can block the view of more distant objects, but not vice versa
  • figures (i.e., foreground objects) tend to have convex borders

The study of visual illusions (cases when the inference process goes wrong) has yielded much insight into what sort of assumptions the visual system makes.

Another type of the unconscious inference hypothesis (based on probabilities) has recently been revived in so-called Bayesian studies of visual perception.[7] Proponents of this approach consider that the visual system performs some form of Bayesian inference to derive a perception from sensory data. Models based on this idea have been used to describe various visual perceptual functions, such as the perception of motion, the perception of depth, and figure-ground perception.[8][9] The “wholly empirical theory of perception” is a related and newer approach that rationalizes visual perception without explicitly invoking Bayesian formalisms.

Gestalt theory

Main article: Gestalt psychology

Gestalt psychologists working primarily in the 1930s and 1940s raised many of the research questions that are studied by vision scientists today.

The Gestalt Laws of Organization have guided the study of how people perceive visual components as organized patterns or wholes, instead of many different parts. “Gestalt” is a German word that partially translates to “configuration or pattern” along with “whole or emergent structure”. According to this theory, there are eight main factors that determine how the visual system automatically groups elements into patterns: Proximity, Similarity, Closure, Symmetry, Common Fate (i.e. common motion), Continuity as well as Good Gestalt (pattern that is regular, simple, and orderly) and Past Experience.

 

,恰是『視覺』『直覺』之『完備』與『不足』的乎??!!

格式塔學派德語Gestalttheorie)是心理學重要流派之一,興起於20世紀初的德國,又稱為完形心理學[1]。由馬科斯·韋特墨(1880-1943)、沃爾夫岡·苛勒(1887-1967)和科特·考夫卡(1886-1941)三位德國心理學家在研究似動現象的基礎上創立。格式塔是德文Gestalt的譯音,意即「模式、形狀、形式」等,意思是指「動態的整體(dynamic wholes)」。

格式塔學派主張人腦的運作原理是整體的,「整體不同於其部件的總和」。例如,我們對一朵花的感知,並非純粹單單從對花的形狀 、顏色、大小等感官資訊而來,還包括我們對花過去的經驗和印象 ,加起來才是我們對一朵花的感知[2]

260px-Reification

 

 

260px-Multistability.svg

 

 

 

260px-Invariance

具體化

具體化(Reification)是知覺的「建設性」的或「生成性的」方面,這種知覺經驗,比起其所基於的感覺刺激,包括了更多外在的空間信息。例如,圖形A可以被知覺為三角形,儘管在事實上並未畫三角形。圖形C可以被視為三維球體,事實上也沒有畫三維球體。

組織性

「組織性」(Multistability或「組織性知覺」multistable perception)是趨勢模糊知覺經驗,不穩定地在兩個或兩個以上不同解釋之間往返。例如左圖所示「內克爾立方體」和「魯賓圖/花瓶幻覺」。

恆常性

恆常性(Invariance) 知覺認可的簡單幾何組件,形成獨立的旋轉,平移、大小以及其他一些變化(如彈性變形,不同的燈光和不同的組件功能)。例如圖例’A’在圖中都立即確認為相 同的基本形式,立即有別於’B’的形式。在彈性變形的’C’,描繪時使用不同的圖形元素,如’D’類。 產生「具體化」、「多重穩定性」、「不變性」和「不可分模塊單獨進行建模」,它們是不同方面的統一機制。

 

一朵活生生之『玫瑰花』是一『整體』,一枝已離株的『玫瑰花』難免凋零。不知誰說︰就算將之『解析』為根、莖、葉、…… 終究沒了『生命』★不過假使不『解析』,它果能活的長久嗎☆

─── 摘自《光的世界︰幾何光學七

 

為何今日臨文

viz

Introduction

The viz package in pydy is designed to facilitate browser based animations for PyDy framework.

Typically the plugin is used to generate animations for multibody systems. The systems are defined with sympy.physics.mechanics, solved numerically with the codegen package and scipy, and then visualized with this package. But the required data for the animations can theorectically be generated by other methods and passed into a Scene object.

The frontend is based on three.js, a popular interface to the WebGraphics Library (WegGL). The package provides a Python wrapper for some basic functionality for Three.js i.e Geometries, Lights, Cameras etc.

 

心遲疑呢?或許等待樹莓派 之 vc4/drm 

OpenGL performance reduced on Raspbian Stretch #79

XECDesign commented on Sep 4

After a bit of testing, it does look like this is an issue which affects software OpenGL rendering in general, not just glxgears. However, the change of behaviour comes from upstream Debian packages and software opengl rendering is not something we’ve ever touched or claimed to support. I would recommend enabling vc4 fkms in raspi-config for proper OpenGL support.

 

證之,果然矣︰

pi@raspberrypi:~ glxinfo | grep -i opengl libGL error: failed to authenticate magic 3 libGL error: failed to load driver: i965 OpenGL vendor string: VMware, Inc. OpenGL renderer string: Gallium 0.4 on llvmpipe (LLVM 3.9, 128 bits) OpenGL core profile version string: 3.3 (Core Profile) Mesa 13.0.6 OpenGL core profile shading language version string: 3.30 OpenGL core profile context flags: (none) OpenGL core profile profile mask: core profile OpenGL core profile extensions: OpenGL version string: 3.0 Mesa 13.0.6 OpenGL shading language version string: 1.30 OpenGL context flags: (none) OpenGL extensions: OpenGL ES profile version string: OpenGL ES 3.0 Mesa 13.0.6 OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.00 OpenGL ES profile extensions: pi@raspberrypi:~

 

然而目前樹莓派 G1 GL

 

還很挑 HDMI 顯示器才開機哩!故置疑焉?

─ 摘自《【鼎革‧革鼎】︰ RASPBIAN STRETCH 《六之 D 》

 

實用化已太久矣!

既然仍需測試,又將進入 4K/5G 的時代,何不直指 Raspberry-Pi 最新的 3B+ 乎?

pi@raspberrypi:~ cat /proc/version  Linux version 4.14.34-v7+ (dc4@dc4-XPS13-9333) (gcc version 4.9.3 (crosstool-NG crosstool-ng-1.22.0-88-g8460611)) #1110 SMP Mon Apr 16 15:18:51 BST 2018  pi@raspberrypi:~ cat /proc/cpuinfo 
processor	: 0
model name	: ARMv7 Processor rev 4 (v7l)
BogoMIPS	: 89.60
Features	: half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 
CPU implementer	: 0x41
CPU architecture: 7
CPU variant	: 0x0
CPU part	: 0xd03
CPU revision	: 4

processor	: 1
model name	: ARMv7 Processor rev 4 (v7l)
BogoMIPS	: 89.60
Features	: half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 
CPU implementer	: 0x41
CPU architecture: 7
CPU variant	: 0x0
CPU part	: 0xd03
CPU revision	: 4

processor	: 2
model name	: ARMv7 Processor rev 4 (v7l)
BogoMIPS	: 89.60
Features	: half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 
CPU implementer	: 0x41
CPU architecture: 7
CPU variant	: 0x0
CPU part	: 0xd03
CPU revision	: 4

processor	: 3
model name	: ARMv7 Processor rev 4 (v7l)
BogoMIPS	: 89.60
Features	: half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 
CPU implementer	: 0x41
CPU architecture: 7
CPU variant	: 0x0
CPU part	: 0xd03
CPU revision	: 4

Hardware	: BCM2835
Revision	: a020d3
Serial		: 00000000e08b738d
pi@raspberrypi:~ </pre>    <span style="color: #666699;">幸而藉著修改</span>  <span style="color: #ff9900;">去掉 --disable-gpu-compositing ︰</span> <pre class="lang:default decode:true">pi@raspberrypi:~ more /etc/chromium-browser/customizations/00-rpi-vars 
CHROMIUM_FLAGS="${CHROMIUM_FLAGS} --disable-quic --enable-tcp-fast-open --disabl
e-gpu-compositing --ppapi-flash-path=/usr/lib/chromium-browser/libpepflashplayer
.so --ppapi-flash-args=enable_stagevideo_auto=0 --ppapi-flash-version="

 

第一步成功的哩!◎

https://get.webgl.org/

 

 

 

 

 

 

 

 

 

STEM 隨筆︰古典力學︰模擬術【三】

派生碼訊

丑 牛

花生日詩》魏塘道中作‧清‧舒位

啼鶯如夢送歸艎,日子平分夜未央。
願取鴛鴦湖裡水,釀成春酒寄花嘗。

雨落風開事偶然,青春初度有情天。
無因細算花年纪,今日分明又一年。

︰事急當緩,緩則圓。問原由?往昔日,避重就輕!

派 ︰手忙拼剪五彩紙,心繫家習圖靈機。剪拼成

張長弓 女兒節娃娃,《誥的

 

,靈犀偶得張良計。

《 網 》 網說︰水調歌頭

水調歌頭,詞牌名。亦稱《花犯念奴》。此調是截取《水調歌》大曲開頭一章的創新之作。

雙調九十五字,前段九句四平韻,後段十句四平韻。

若應『女兒節』,或選『黃庭堅』。

蘇軾

明月幾時有?把酒問青天。不知天上宮闕,今夕是何年。我欲乘風歸去,又恐瓊樓玉宇,高處不勝寒。起舞弄清影,何似在人間 。

轉朱閣,低綺戶,照無眠。不應有恨,何事長向別時圓?人有悲歡離合,月有陰晴圓缺,此事古難全。但願人長久,千里共嬋娟 。

【詞牌格式】

註:表示平聲,表示仄聲,表示本仄可平,表示本平可仄,粗體表示韻腳。

(上六下五或上四下七)。

(上六下五或上四下七,又或作)。

黃庭堅

瑤草一何碧,春入武陵溪。溪上桃花無數,花上有黃鸝,我欲穿花尋路,直入白雲深處,浩氣展虹霓。只恐花深里,紅露濕人衣 。

坐玉石,欹玉枕,拂金徽。謫仙何處,天人伴我白螺杯。我為靈芝仙草,不為朱唇丹臉,長嘯亦何為!醉舞下山去,明月逐人歸 。

─── 《M♪O 之學習筆記本《丑》控制︰【䷝】輕重緩急

 

本來心頭輕,不覺哼唱起《水調歌頭》!陡然接上了、想起了 『ㄏㄓ 計畫』的失敗?當下惆悵很,

不知那寫『正反器』

尚待考

一位元記憶體縱使不得記幾刻!終是本源大道生,何苦太相逼! !莫戀貪愛有 S ,有時伴 R 更能相宜 。恐有無常時,漂泊世事,可嘆總難定。胡不就盡情盡興,吟這

RS 正反器之《紅樓夢》曲,念那

《水調歌頭》的憶。

 

程式、歷經《變形記》的 M♪O  ,今日好不好 …… 的呢??

怎地又會懷想起過往之事︰

話說︰三更有夢書當枕。怎曉書滑人清醒??僅就所記之言,鋪陳一番《企鵝的復國》,以為寓言罷了!! ───

之 『ㄏㄓ 計畫』失敗之後。那時兩極大半已崩解,海平面上升吞噬著大地,四處常有狂風暴雨,一日可睹四季異象。這《卡夫卡村》就是那『企鵝小學堂』的現址, M♪o 的執教處也。據 W!o 說︰這個『變形祭』是 M♪o 達觀面對後所始,當『長陽之祀』因怨『日』廢止之後,早就沒有『飛龍祭』的了。社會上瀰漫著『踏天無望』之情,眼只見『亢龍有悔』之境。於是高唱教育無用論 ,何不及時行樂,以免悔不當初!因此 M♪o 以科學生活化為經,技術日常化為緯,帶領熱情的學生們重新打造自己家園。經過幾年的辛勤努力,感動了當地眾人紛紛投入創造運動。因為經常於『秋雪』來臨前,慶收一年的耕耘成果,久而久之,就正式命名為『變形祭 』的了,以為傳承『科技護生』之旨。然而許多人都不了解 M♪o 為什麼會采『變形記』初版之封面圖,作為『變形祭 』的標誌之故?這是因為『初』『化』二字使然。所謂『變形』Transformation 之義,重在『變化』之『化』,其要在『化』之『初』。若是用 M♪o 的說法︰『化』化,教行也。因形近『 It 』,故假借來象徵 Intelligent technology 。千萬別跟『 甲骨文它 』『它』混淆,《 文 》文說︰

它,虫也。从虫而長,象冤曲垂尾形。上古艸居患它,故相問無它乎。凡它之屬皆从它。蛇,它或从虫。

要是弄錯了豈不可笑也!!然而『 It 』智慧科技的傳播力大,而且各種『 It 裝置』『形變』『井通』『貫串』成了『 It 網』阡陌縱橫利益彼此, M♪o 也只能置之一笑,無可如何的了。

行文至此,一時惘然,雖說眼見表面容易,探究事實底蘊困難,更何況還是他鄉之『物』 It ,又缺乏適當範本,看來只好求其神韻,也用借假修真之法,比之擬之僅止形似,徒遺笑於大方之家吧!?

─── 摘自《勇闖新世界︰ W!O《卡夫卡村》變形祭︰品味科學‧教具教材‧甲子又興元

 

哩!!

說來時代變遷一去不回頭,只剩下餘波蕩漾矣!★

n07_simulation.ipynb

 

終究盼望再興昇平之世呦?☆

yeadon

The human inertia model developed by Fred Yeadon in 1990. https://pypi.python.org/pypi/yeadon

yeadon

Latest PyPI version Number of PyPI downloads Documentation Status https://travis-ci.org/chrisdembia/yeadon.png?branch=master

This package calculates the masses, center of mass positions, and inertia tensors that correspond to the human inertia model developed by Yeadon in (Yeadon, 1990). The package allows for the input of both measurements and configuration variables (joint angles), and provides 3D visualization using the MayaVi package. See the online documentation at http://yeadon.readthedocs.org/.

References

M. R. Yeadon, 1990. The Simulation of Aerial Movement-ii. Mathematical Inertia Model of the Human Body. Journal of Biomechanics, 23:67-74.

……

Welcome to yeadon‘s documentation!

This package calculates the masses, center of mass positions, and inertia tensors that correspond to the human inertia model developed by Yeadon [1]. The package allows for the input of both measurements from human subjects and configuration variables (joint angles) with which one can orient the model. Additionally, the package allows for 3D visualization of the model using the package.

One possible use of the package is to incorporate the inertial properties of an actual human into a rigid body dynamics model that contains a human. Then, the model containing the human can be compared to experiments performed with the same human.

This package was developed during the Summer of 2011 at the University of California, Davis, to aid with the bicycle research of Jason Moore and Dale Luke Peterson in the Sports Biomechanics Lab of Professor Mont Hubbard. Jason Moore had a multibody dynamics model of a human riding a bicycle, and performed experiments with humans riding a bicycle. To compare his model to his experiments, he needed the inertial properties of the human riding the bicycle. That’s what this package was able to provide him [2]. Learn more about the Sports Biomechanics Lab atbiosport.ucdavis.edu.

Here is a video that introduces the basics of this package: http://youtu.be/o-5Ss6YLY0I.

───

 

 

 

 

 

 

 

STEM 隨筆︰古典力學︰模擬術【二】

承上篇,那時腦海裡閃過派生『字典』

5.5. Dictionaries

Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.

Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use sorted(d.keys()) instead). [2] To check whether a single key is in the dictionary, use thein keyword.

 

資料結構本無『次序』!方才想起,只在安裝 PyDy 時,讀了一下

PyDy Package’s documentation!

 

及其範例,就匆匆上路了,果然記不牢乎?

只得自食其言,也來『補過』呦★

重讀

system

Introduction

The System class manages the simulation (integration) of a system whose equations are given by KanesMethod.

Many of the attributes are also properties, and can be directly modified.

Here is the procedure for using this class.

  1. specify your options either via the constructor or via the attributes.
  2. optionally, call generate_ode_function() if you want to customize how the ODE function is generated.
  3. call integrate() to simulate your system.

Examples

The simplest usage of this class is as follows. First, we need a KanesMethod object on which we have already invoked kanes_equations():

km = KanesMethod(...)
km.kanes_equations(force_list, body_list)
times = np.linspace(0, 5, 100)
sys = System(km, times=times)
sys.integrate()

In this case, we use defaults for the numerical values of the constants, specified quantities, initial conditions, etc. You probably won’t like these defaults. You can also specify such values via constructor keyword arguments or via the attributes:

※ 註︰ symbol 與 dynamicsymbol 須加 “s” 。此改過。

sys = System(km,
             initial_conditions={dynamicsymbols('q1'): 0.5},
             times=times)
sys.constants = {symbols('m'): 5.0}
sys.integrate()

To double-check the constants, specifieds, states and times in your problem, look at these properties:

sys.constants_symbols
sys.specifieds_symbols
sys.states
sys.times

In this case, the System generates the numerical ode function for you behind the scenes. If you want to customize how this function is generated, you must call generate_ode_function on your own:

sys = System(KM)
sys.generate_ode_function(generator='cython')
sys.integrate()

 

後,豁然開朗也☆

 

 

 

 

 

 

 

STEM 隨筆︰古典力學︰模擬術【一】

才想可以快速通過

n07_simulation.ipynb

 Now that we have the symbolic equations of motion we need to transform them into Python functions that can be evaluated for use in numerical integration. Numerical integration is required to solve the ordinary differential initial value problem and allow us to see how the states change through time.

 

筆記文本,輕輕飛越『動態模擬』

Dynamical simulation

Dynamical simulation, in computational physics, is the simulation of systems of objects that are free to move, usually in three dimensions according to Newton’s laws of dynamics, or approximations thereof. Dynamical simulation is used in computer animation to assist animators to produce realistic motion, in industrial design (for example to simulate crashes as an early step in crash testing), and in video games. Body movement is calculated using time integration methods.

Physics engines

In computer science, a program called a physics engine is used to model the behaviors of objects in space. These engines allow simulation of the way bodies of many types are affected by a variety of physical stimuli. They are also used to create Dynamical simulations without having to know anything about physics. Physics engines are used throughout the video game and movie industry, but not all physics engines are alike; They are generally broken into real-time and the high precision but these are not the only options. Most real-time physics engines are inaccurate and yield only the barest approximation of the real world, whereas most high-precision engines are far too slow for use in everyday applications. To understand how these Physics engines are built, a basic understanding of physics is required. Physics engines are based on the actual behaviors of the world as described by classical mechanics. Engines do not typically account for Modern Mechanics (see Theory of relativity and quantum mechanics) because most visualization deals with large bodies moving relatively slowly, but the most complicated engines perform calculations for Modern Mechanics as well as Classical. The models used in Dynamical simulations determine how accurate these simulations are.

 

語詞叢林!只需介紹一下 PyDy 之

codegen

Introduction

The pydy.codegen package contains various tools to generate numerical code from symbolic descriptions of the equations of motion of systems. It allows you to generate code using a variety of backends depending on your needs. The generated code can also be auto-wrapped for immediate use in a Python session or script. Each component of the code generators and wrappers are accessible so that you can use just the raw code or the wrapper versions.

We currently support three backends:

lambdify
This generates NumPy-aware Python code which is defined in a Python lambda function, using the sympy.utilities.lambdify module and is the default generator.
Theano
This generates Theano trees that are compiled into low level code, using thesympy.printers.theano_code module.
Cython
This generates C code that can be called from Python, using SymPy’s C code printer utilities and Cython.

 

的用法!!何況早有範例也。

Example Use

The simplest entry point to the code generation tools is through the System class.

>>> from pydy.models import multi_mass_spring_damper
>>> sys = multi_mass_spring_damper()
>>> type(sys)
<class 'pydy.system.System'>
>>> rhs = sys.generate_ode_function()
>>> help(rhs) # rhs is a function:
Returns the derivatives of the states, i.e. numerically evaluates the right
hand side of the first order differential equation.

x' = f(x, t, p)

Parameters
==========
x : ndarray, shape(2,)
    The state vector is ordered as such:
        - x0(t)
        - v0(t)
t : float
    The current time.
p : dictionary len(3) or ndarray shape(3,)
    Either a dictionary that maps the constants symbols to their numerical
    values or an array with the constants in the following order:
        - m0
        - c0
        - k0

Returns
=======
dx : ndarray, shape(2,)
    The derivative of the state vector.


>>> import numpy as np
>>> rhs(np.array([1.0, 2.0]), 0.0, np.array([1.0, 2.0, 3.0]))
array([ 2., -7.])

 

怎知一跑跑了 n 次?只因結果會不一樣勒??

突然發現 m_0 , c_0, k_0  help 排列次序,為何每每不同耶??!!

 

故爾鼻子摸著閱讀『原始碼』︰

Source code for pydy.models

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""This module contains some sample symbolic models used for testing and
examples."""

# external libraries
import sympy as sm
import sympy.physics.mechanics as me

# local
from .system import System


[docs]def multi_mass_spring_damper(n=1, apply_gravity=False,
                             apply_external_forces=False):
    """Returns a system containing the symbolic equations of motion and
    associated variables for a simple mutli-degree of freedom point mass,
    spring, damper system with optional gravitational and external
    specified forces. For example, a two mass system under the influence of
    gravity and external forces looks like:

    ::

        ----------------
         |     |     |   | g
         \    | |    |   V
      k0 /    --- c0 |
         |     |     | x0, v0
        ---------    V
        |  m0   | -----
        ---------    |
         | |   |     |
         \ v  | |    |
      k1 / f0 --- c1 |
         |     |     | x1, v1
        ---------    V
        |  m1   | -----
        ---------
           | f1
           V

    Parameters
    ----------
    n : integer
        The number of masses in the serial chain.
    apply_gravity : boolean
        If true, gravity will be applied to each mass.
    apply_external_forces : boolean
        If true, a time varying external force will be applied to each mass.

    Returns
    -------
    system : pydy.system.System
        A system constructed from the KanesMethod object.

    """

 

卻是一無所獲!!??

只能死馬當活馬醫,扒文

codegen API

pydy.codegen.ode_function_generators.generate_ode_function(*args, **kwargs)

Generates a numerical function which can evaluate the right hand side of the first order ordinary differential equations from a system described by one of the following three symbolic forms:

[1] x’ = F(x, t, r, p)

[2] M(x, p) x’ = F(x, t, r, p)

[3] M(q, p) u’ = F(q, u, t, r, p)
q’ = G(q, u, t, r, p)

where

x : states, i.e. [q, u] t : time r : specified (exogenous) inputs p : constants q : generalized coordinates u : generalized speeds M : mass matrix (full or minimum) F : right hand side (full or minimum) G : right hand side of the kinematical differential equations

The generated function is of the form F(x, t, p) or F(x, t, r, p) depending on whether the system has specified inputs or not.

Parameters:

right_hand_side : SymPy Matrix, shape(n, 1)

A column vector containing the symbolic expressions for the right hand side of the ordinary differential equations. If the right hand side has been solved for symbolically then only F is required, see form [1]; if not then the mass matrix must also be supplied, see forms [2, 3].

coordinates : sequence of SymPy Functions

The generalized coordinates. These must be ordered in the same order as the rows in M, F, and/or G and be functions of time.

speeds : sequence of SymPy Functions

The generalized speeds. These must be ordered in the same order as the rows in M, F, and/or G and be functions of time.

constants : sequence of SymPy Symbols

All of the constants present in the equations of motion. The order does not matter.

mass_matrix : sympy.Matrix, shape(n, n), optional

This can be either the “full” mass matrix as in [2] or the “minimal” mass matrix as in [3]. The rows and columns must be ordered to match the order of the coordinates and speeds. In the case of the full mass matrix, the speeds should always be ordered before the speeds, i.e. x = [q, u].

coordinate_derivatives : sympy.Matrix, shape(m, 1), optional

If the “minimal” mass matrix, form [3], is supplied, then this column vector represents the right hand side of the kinematical differential equations.

specifieds : sequence of SymPy Functions

The specified exogenous inputs to the system. These should be functions of time and the order does not matter.

linear_sys_solver : string or function

Specify either numpy or scipy to use the linear solvers provided in each package or supply a function that solves a linear system Ax=b with the call signature x = solve(A, b). For example, if you need to use custom kwargs for the SciPy solver, pass in a lambda function that wraps the solver and sets them.

constants_arg_type : string

The generated function accepts two different types of arguments for the numerical values of the constants: either a ndarray of the constants values in the correct order or a dictionary mapping the constants symbols to the numerical values. If None, this is determined inside of the generated function and can cause a significant slow down for performance critical code. If you know apriori what arg types you need to support choose either array or dictionary. Note that array is faster than dictionary.

specifieds_arg_type : string

The generated function accepts three different types of arguments for the numerical values of the specifieds: either a ndarray of the specifieds values in the correct order, a function that generates the correctly ordered ndarray, or a dictionary mapping the specifieds symbols or tuples of thereof to floats, ndarrays, or functions. If None, this is determined inside of the generated function and can cause a significant slow down for performance critical code. If you know apriori what arg types you want to support choose either array, function, or dictionary. The speed of each, from fast to slow, are array, function, dictionary, None.

generator : string or and ODEFunctionGenerator, optional

The method used for generating the numeric right hand side. The string options are {‘lambdify’|’theano’|’cython’} with ‘lambdify’ being the default. You can also pass in a custom subclass of ODEFunctionGenerator.

Returns:

rhs : function

A function which evaluates the derivaties of the states. See the function’s docstring for more details after generation.

Notes

The generated function still supports the pre-0.3.0 extra argument style, i.e. args = {‘constants’: …, ‘specified’: …}, but only if constants_arg_type and specifieds_arg_type are both set to None. This functionality is deprecated and will be removed in 0.4.0, so it’s best to adjust your code to support the new argument types. See the docstring for the generated function for more info on the new style of arguments.

 

忽恍然大悟,後哈哈大笑呦◎