url stringlengths 11 2.25k | text stringlengths 88 50k | ts timestamp[s]date 2026-01-13 08:47:33 2026-01-13 09:30:40 |
|---|---|---|
https://aws.amazon.com/blogs/networking-and-content-delivery/implementing-consistent-dns-query-logging-with-amazon-route-53-profiles/ | Implementing consistent DNS Query Logging with Amazon Route 53 Profiles | Networking & Content Delivery Skip to Main Content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Blogs Home Blogs Editions Networking & Content Delivery Implementing consistent DNS Query Logging with Amazon Route 53 Profiles by Aanchal Agrawal and Anushree Shetty on 05 JAN 2026 in Amazon Route 53 , AWS Transit Gateway , Intermediate (200) , Networking & Content Delivery , Resource Access Manager (RAM) , Security, Identity, & Compliance Permalink Share Managing DNS query logging across multiple Amazon Virtual Private Clouds (VPCs) has long been a significant challenge for enterprise teams. The traditional approach required manual configuration of DNS query logging for each VPC individually, creating a cascade of operational problems. This fragmented process led to inconsistent implementation across different environments, compliance gaps due to missed or misconfigured VPCs, and substantial operational burden from repetitive manual setup tasks. Teams often found themselves lacking comprehensive visibility into DNS activities across their entire AWS footprint, making troubleshooting complex when issues spanned multiple VPCs. We’re excited to announce a solution that addresses these pain points head-on. Amazon Route 53 Resolver Query Logging now integrates seamlessly with Amazon Route 53 Profiles , offering enterprise teams a centralized approach to DNS query management. You can use Route 53 Resolver Query Logging to log DNS queries that originate in your Amazon VPCs. With query logging enabled, you can observe which domain names have been queried, the AWS resources from which the queries originated, and the responses that were received. This intermediate level post highlights integration of Route 53 Profiles with Route 53 Resolver Query Logging. You can use Route 53 Profiles to simplify the management of DNS Query Logging, configuring logging once at the Profile level with automatic propagation to all associated VPCs, removing manual per-VPC configuration while providing consistent logging policies across expanding AWS infrastructures. This centralization significantly reduces operational complexity and management overhead, streamlines compliance verification, and prevents configuration drift across large-scale VPC deployments. The integration uses AWS Resource Access Manager (AWS RAM) to facilitate secure sharing of these configurations across organizational boundaries, so that even the most complex multi-account architectures maintain comprehensive DNS visibility. This technical guide is designed for administrators, cloud architects, and security professionals who manage multi-account AWS environments with complex DNS configurations. You’ll discover how to dramatically reduce management overhead while strengthening security visibility and governance across your infrastructure. To get the most from this post, we recommend having foundational knowledge of key AWS networking services—including Amazon VPC, Amazon Route 53 Resolver , Amazon Route 53 Profiles, and AWS RAM along with basic DNS principles. What are Route 53 Profiles? Route 53 Profiles enables consistent DNS management so that you can establish standardized DNS configurations called Profiles, which encapsulate comprehensive DNS settings. These Profiles maintain uniformity across your DNS infrastructure by incorporating private hosted zones and their configurations, Route 53 Resolver rules (encompassing both forwarding and system rules), DNS Firewall rule groups, and Interface VPC endpoints. The Profile directly manages certain VPC-level DNS configurations, such as Reverse DNS lookup configuration for Resolver Rules, DNS Firewall failure mode configuration, and DNSSEC validation configuration. You can define DNS settings once and apply them consistently across multiple VPCs and AWS accounts, streamlining management, providing uniformity and consistency, and enhancing scalability as your AWS environment grows. This centralized approach streamlines DNS administration by automatically propagating updates to all associated VPCs. AWS RAM facilitates Profile sharing for cross-account management within the same AWS Region. Route 53 Resolver Query Logging Route 53 Resolver Query Logging logs all DNS queries processed by Route 53, the ones that originate from your VPC resources (such as Amazon Elastic Compute Cloud (Amazon EC2) instances, containers, or AWS Lambda functions) and the traffic processed by Route 53 Resolver endpoints. The logs capture information for queries that: Resolve local VPC DNS names Resolve to Route 53 private hosted zones Are forwarded to on-premises DNS servers through Route 53 Resolver Endpoints Are resolved over the public internet By default, all VPCs use the Route 53 Resolver to resolve DNS queries, and this feature captures a record of those requests and their responses. Each log entry includes the VPC ID, query timestamp, domain name requested (Query Name), type of DNS record sought (Query Type), DNS response code (such as NOERROR or NXDOMAIN), and the specific source IP and resource ID that initiated the query. When these logs are enabled, they publish to a central destination for analysis and retention, such as Amazon Simple Storage Service (Amazon S3) , Amazon CloudWatch Logs , or Amazon Kinesis Data Firehose , with the requirement that these destinations must reside in the same Region as the query logging configuration. Route 53 Resolver Query Logging delivers essential visibility into your network’s DNS activity. It functions as a critical security tool for detecting malicious activity such as malware communication or data exfiltration via anomalous DNS queries. For compliance and audit purposes, it provides a detailed record of all name resolution activity. The service troubleshoots and creates a visibility pane for you to quickly diagnose DNS failures by revealing the source, the domain requested, and the response received. Challenges with consistent Route 53 Resolver Query Logging Maintaining a consistent DNS query logging with Route 53 Resolver involves creating query logging configurations in an AWS account and sharing these configurations with multiple accounts using AWS RAM. Therefore, each account can associate its VPCs with the shared logging configuration, so that logs can be collected in a centralized location such as CloudWatch Logs or an S3 bucket. However, challenges exist in this approach, including hard limits on the number of VPCs that can be associated per account and per AWS Region (typically 100) , and the fact that only the owning account can modify or delete the shared configurations. If the shared logging configuration is deleted or unshared, then DNS query logging stops for all associated VPCs, which can complicate management. Furthermore, implementing a unified logging solution that consolidates logs across multiple VPCs and accounts introduces significant complexity and increases the potential for configuration errors. Similarly, designing separate centralized logging systems for different environments (such as development, testing, and production) necessitates careful architecture and maintenance to avoid reliability issues. Integration with Route 53 Profiles You can use this new feature, Route 53 Resolver Query Logging integration with Route 53 Profiles, to implement DNS query logging across multiple VPCs through a single Profile configuration. This removes the need to configure logging separately for each VPC. Key benefits with this integration: Consistent configuration: Previously, DNS Query Logging implementation necessitated individual manual configuration for each Amazon Virtual Private Cloud (Amazon VPC) , resulting in considerable administrative burden as environments expanded. The introduction of Route 53 Profiles transforms this experience through centralized management, so that now you can configure Query Logging once at the Profile level, and the settings propagate automatically to all associated VPCs. This significant enhancement reduces operational complexity and provides consistent logging implementation across your growing AWS infrastructure. Operational efficiency: Network administrators define query logging configurations once and apply them consistently across their infrastructure, significantly reducing management overhead. Scale management: Enterprises managing large VPC fleets implement consistent logging policies through centralized profiles rather than managing individual configurations. Simplified compliance: Security teams ensure all VPCs adhere to logging requirements by associating them with properly configured profiles, making compliance verification clearer. Reduced configuration drift: Organizations can centralize logging configurations in profiles to minimize the risk of inconsistent settings across their environment. The integration works seamlessly with existing log destinations, supporting CloudWatch Logs, Amazon S3, and Amazon Kinesis Data Firehose. When a VPC is associated with a profile containing query logging configurations, DNS queries from that VPC are automatically logged to the specified destinations Centralizing and associating Route 53 Resolver Query Logging across accounts Prior to this launch, centralizing DNS query logs was a more cumbersome process to manage. In this section we examine the following two figures. Both figures share several common elements: An AWS Region encompassing all of the resources A Production account with a Production VPC A Development (Dev) account with a Dev VPC A Shared Services account with a Shared Services VPC A pre-configured AWS Transit Gateway in the Shared Services Account The Transit Gateway has attachments to the Shared Services VPC, Production VPC, and the Dev VPC Route 53 Resolver Query Logging enabled in the Shared Services Account AWS RAM for resource sharing Associating Route 53 Resolver Query Logging across accounts without Route 53 Profiles First we investigate Figure 1 and follow the steps for how Route 53 Resolver Query Logging was shared across different AWS accounts. Figure 1: Traditional approach – Sharing Route 53 Resolver Query Logging with other accounts without using Route 53 Profiles Based on Figure 1, these are the steps that were followed: Enable Route 53 Resolver Query Logging in the Shared Services account. The Query Logging is then shared with the other two accounts (Production and Dev) through AWS RAM as per Steps 2–4 When it is shared with the other accounts, Query logging needs to be manually associated with the VPCs. Associating Route 53 Resolver Query Logging across accounts with Route 53 Profiles With the Route 53 Profiles as shown in Figure 2, the process is streamlined: Figure 2: Sharing Amazon Route 53 Resolver Query Logging via Amazon Route 53 Profile Based on Figure 2, the steps would be as follows: Enable Route 53 Resolver Query Logging in the Shared Services account. Create a Route 53 Profiles in the Shared Services account. Associate Route 53 Resolver Query Logging with the Route 53 Profile. The Route 53 Profiles is shared with the Production and Dev accounts through AWS RAM. Associate the Production and Dev VPCs with the Profile. The VPCs automatically gain access to Route 53 Resolver Query Logging through their association (you can find the steps to associate resources in the Route 53 Profiles association documentation provided) with the Route 53 Profiles. Before this feature was launched, enabling Query Logging necessitated manual configuration for each Amazon VPC individually. This created significant operational overhead as infrastructure grew. Route 53 Profiles streamlines this process by attaching Query Logging to a Profile. In turn, the logging configuration is automatically applied to all VPCs associated with that Profile, thus streamlining management at scale. Dual association scenario If a VPC has both a direct Route 53 Resolver Query Logging association and Route 53 Profile based association, then the logs are generated and stored in two separate locations and may result in duplicate logging. To prevent redundant logging entries, implement a staged transition when adopting Profile-based query logging. First, create and associate your new logging configuration with the appropriate Profiles, then validate its proper functioning, and finally remove any pre-existing query logging configurations by stopping the logging from the VPCs and deleting it for the ones that are directly associated with individual VPCs. Direct VPC association logs maintain the existing format: (vpc-id_instance-id) Profile-based association logs use the new format: (profile-id_vpc-id_instance-id) Key considerations for centralizing Route 53 Resolver Query Logging with Route 53 Profiles Sharing resources with Route 53 Profiles works only within the same Region. The account with which the resources have been shared can’t modify or delete the configuration. If the configuration is deleted or unshared, then consolidated logging stops for all of the associated VPCs. Cross-account resource sharing through AWS RAM necessitates that both the resource owner and the sharing account have appropriate AWS Identity and Access Management (IAM) permissions to create and manage the resource share. Without these permissions, access is restricted, and effective sharing or management of resources cannot be established. You can read more about the permissions in the AWS RAM documentation . Consolidated logging enhances data governance by enabling consistent access controls and minimizing human access, with automated systems handling read operations. Implement monitoring to alert on any write or admin access to the log storage. Route 53 Profiles and Route 53 Query logging offer comprehensive support for both IPv4 and IPv6 protocols. This provides full compatibility with modern network environments. Furthermore, organizations can use this dual-protocol support to effectively manage and monitor DNS queries across both address formats, providing enhanced visibility and control over network traffic regardless of the IP version in use. Availability and pricing Route 53 Profiles is available in all AWS Regions except Asia Pacific (New Zealand) and Asia Pacific (Taipei). For Route 53 Resolver Query logging the primary charges aren’t for the logging feature itself but for the downstream services used for log storage and analysis. Check CloudWatch Pricing , Amazon S3 Pricing , Amazon Data Firehose Pricing , and Amazon Athena Pricing for individual pricing. Apart from the preceding costs, Route 53 Profile charges also apply. AWS designed the pricing model for maximum scalability and value, featuring a transparent, hourly, pay-as-you-go structure based on your Profile-VPC associations. Conclusion Integrating DNS query logging with Amazon Route 53 Profiles offers five key advantages. Route 53 Profiles revolutionizes Amazon Query Logging by replacing manual per-VPC configurations with a centralized management approach where settings automatically propagate to all associated VPCs. This integration significantly reduces operational overhead for network teams who can now define consistent logging policies once and apply them across their entire infrastructure regardless of scale. The solution also enables cross-account sharing of DNS configurations through AWS RAM, facilitating multi-account governance while streamlining compliance verification. Furthermore, organizations can remove the need for multiple manual configurations to minimize configuration drift risk and maintain uniform advanced settings across their growing AWS environment. This blog post showed how to set up DNS query logging using Route 53 Profile and offered guidance for organizations with the traditional architectures. We examined the difficulties associated with conventional solutions and walked through the detailed implementation process and recommended practices for incorporating DNS query logging with Route 53 Profiles. For additional information, check out these resources: Route 53 Profiles Amazon Route 53 Resolver Query Logging AWS Resource Access Manager About the authors Aanchal Agrawal Aanchal holds the position of Senior Technical Account Manager at AWS, where she specializes in Networking and Edge Security. Throughout her time at AWS, she has concentrated on aiding customers in effective cloud adoption. Leveraging her expertise in networking and edge security, she assists clients in constructing efficient and optimized cloud architectures. Anushree Shetty Anushree works as Senior Technical Account Manager at AWS. She specializes in Perimeter Protection and Edge services. She guides organizations through seamless AWS Edge migrations, crafting tailored cloud solutions that address specific business requirements and security needs. She consistently helps customers maximize the benefits of their cloud adoption, enhancing both their security posture and operational efficiency. Resources Networking Products Getting Started Amazon CloudFront Follow Twitter Facebook LinkedIn Twitch Email Updates Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms <a data-rg-n="Link" href="#" data-rigel-analytics="{"name":"Link","properties":{"size":2}}" class="rgft_8711ccd9 rgft_98b54368 rgft_13008707 rgft_27323f | 2026-01-13T09:30:39 |
https://github.com/yangshun/front-end-interview-handbook/edit/main/contents/companies/canva-front-end-interview-questions.md | Sign in to GitHub · GitHub Skip to content You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert Sign in to GitHub {{ message }} --> Username or email address Password Forgot password? Uh oh! There was an error while loading. Please reload this page . New to GitHub? Create an account Sign in with a passkey Terms Privacy Docs Contact GitHub Support Manage cookies Do not share my personal information You can’t perform that action at this time. | 2026-01-13T09:30:39 |
https://id-id.facebook.com/r.php?next=https%3A%2F%2Fwww.facebook.com%2Fshare_channel%2F%3Ftype%3Dreshare%26link%3Dhttps%253A%252F%252Fdev.to%252Ftatyanabayramova%252Fglaucoma-awareness-month-363o%26app_id%3D966242223397117%26source_surface%3Dexternal_reshare%26display%26hashtag&amp%3Bamp%3Bamp%3Bamp%3Blocale=id_ID&amp%3Bamp%3Bamp%3Bamp%3Bdisplay=page&amp%3Bamp%3Bamp%3Bamp%3Bentry_point=login | Facebook Facebook Email atau telepon Kata Sandi Lupa akun? Daftar Anda Diblokir Sementara Anda Diblokir Sementara Sepertinya Anda menyalahgunakan fitur ini dengan menggunakannya terlalu cepat. Anda dilarang menggunakan fitur ini untuk sementara. Back Bahasa Indonesia 한국어 English (US) Tiếng Việt ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch Daftar Masuk Messenger Facebook Lite Video Meta Pay Meta Store Meta Quest Ray-Ban Meta Meta AI Konten Meta AI lainnya Instagram Threads Pusat Informasi Pemilu Kebijakan Privasi Pusat Privasi Tentang Buat Iklan Buat Halaman Developer Karier Cookie Pilihan Iklan Ketentuan Bantuan Pengunggahan Kontak & Non-Pengguna Pengaturan Log aktivitas Meta © 2026 | 2026-01-13T09:30:39 |
https://www.sqlite.org/releaselog/3_38_0.html | SQLite Release 3.38.0 On 2022-02-22 Small. Fast. Reliable. Choose any three. Home Menu About Documentation Download License Support Purchase Search About Documentation Download Support Purchase Search Documentation Search Changelog SQLite Release 3.38.0 On 2022-02-22 Added the -> and ->> operators for easier processing of JSON. The new operators are compatible with MySQL and PostgreSQL. The JSON functions are now built-ins. It is no longer necessary to use the -DSQLITE_ENABLE_JSON1 compile-time option to enable JSON support. JSON is on by default. Disable the JSON interface using the new -DSQLITE_OMIT_JSON compile-time option. Enhancements to date and time functions : Added the unixepoch() function . Added the auto modifier and the julianday modifier . Rename the printf() SQL function to format() for better compatibility. The original printf() name is retained as an alias for backwards compatibility. Added the sqlite3_error_offset() interface, which can sometimes help to localize an SQL error to a specific character in the input SQL text, so that applications can provide better error messages. Enhanced the interface to virtual tables as follows: Added the sqlite3_vtab_distinct() interface. Added the sqlite3_vtab_rhs_value() interface. Added new operator types SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET . Added the sqlite3_vtab_in() interface (and related) to enable a virtual table to process IN operator constraints all at once, rather than processing each value of the right-hand side of the IN operator separately. CLI enhancements: Columnar output modes are enhanced to correctly handle tabs and newlines embedded in text. Added options like "--wrap N", "--wordwrap on", and "--quote" to the columnar output modes . Added the .mode qbox alias. The .import command automatically disambiguates column names. Use the new sqlite3_error_offset() interface to provide better error messages. Query planner enhancements: Use a Bloom filter to speed up large analytic queries. Use a balanced merge tree to evaluate UNION or UNION ALL compound SELECT statements that have an ORDER BY clause. The ALTER TABLE statement is changed to silently ignores entries in the sqlite_schema table that do not parse when PRAGMA writable_schema=ON . Hashes: SQLITE_SOURCE_ID: 2022-02-22 18:58:40 40fa792d359f84c3b9e9d6623743e1a59826274e221df1bde8f47086968a1bab SHA3-256 for sqlite3.c: a69af0a88d59271a2dd3c846a3e93cbd29e7c499864f6c0462a3b4160bee1762 A complete list of SQLite releases in a single page and a chronology are both also available. A detailed history of every check-in is available at SQLite version control site . | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/DemangleConfig_8h.html | LLVM: include/llvm/Demangle/DemangleConfig.h File Reference LLVM  22.0.0git include llvm Demangle Macros DemangleConfig.h File Reference #include "llvm/Config/llvm-config.h" #include <cassert> Go to the source code of this file. Macros #define  __has_feature (x) #define  __has_cpp_attribute (x) #define  __has_attribute (x) #define  __has_builtin (x) #define  DEMANGLE_GNUC_PREREQ (maj, min, patch) #define  DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_UNREACHABLE #define  DEMANGLE_ATTRIBUTE_NOINLINE #define  DEMANGLE_DUMP_METHOD     DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_FALLTHROUGH #define  DEMANGLE_ASSERT (__expr, __msg) #define  DEMANGLE_NAMESPACE_BEGIN    namespace llvm { namespace itanium_demangle { #define  DEMANGLE_NAMESPACE_END    } } #define  DEMANGLE_ABI   DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Macro Definition Documentation ◆  __has_attribute #define __has_attribute ( x ) Value: 0 Definition at line 30 of file DemangleConfig.h . ◆  __has_builtin #define __has_builtin ( x ) Value: 0 Definition at line 34 of file DemangleConfig.h . ◆  __has_cpp_attribute #define __has_cpp_attribute ( x ) Value: 0 Definition at line 26 of file DemangleConfig.h . ◆  __has_feature #define __has_feature ( x ) Value: 0 Definition at line 22 of file DemangleConfig.h . ◆  DEMANGLE_ABI #define DEMANGLE_ABI DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Definition at line 115 of file DemangleConfig.h . Referenced by llvm::ms_demangle::Node::output() , parse_discriminator() , and llvm::ms_demangle::Demangler::~Demangler() . ◆  DEMANGLE_ASSERT #define DEMANGLE_ASSERT ( __expr , __msg  ) Value: assert ((__expr) && (__msg)) assert assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!") Definition at line 94 of file DemangleConfig.h . Referenced by OutputBuffer::back() , PODSmallVector< Node *, 8 >::back() , ExplicitObjectParameter::ExplicitObjectParameter() , SpecialSubstitution::getBaseName() , AbstractManglingParser< Derived, Alloc >::OperatorInfo::getSymbol() , OutputBuffer::insert() , PODSmallVector< Node *, 8 >::operator[]() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnresolvedName() , PODSmallVector< Node *, 8 >::pop_back() , AbstractManglingParser< Derived, Alloc >::popTrailingNodeArray() , PODSmallVector< Node *, 8 >::shrinkToSize() , Node::visit() , and AbstractManglingParser< Derived, Alloc >::ScopedTemplateParamList::~ScopedTemplateParamList() . ◆  DEMANGLE_ATTRIBUTE_NOINLINE #define DEMANGLE_ATTRIBUTE_NOINLINE Definition at line 69 of file DemangleConfig.h . ◆  DEMANGLE_ATTRIBUTE_USED #define DEMANGLE_ATTRIBUTE_USED Definition at line 53 of file DemangleConfig.h . ◆  DEMANGLE_DUMP_METHOD #define DEMANGLE_DUMP_METHOD    DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED Definition at line 73 of file DemangleConfig.h . Referenced by Node::dump() . ◆  DEMANGLE_FALLTHROUGH #define DEMANGLE_FALLTHROUGH Definition at line 85 of file DemangleConfig.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseType() . ◆  DEMANGLE_GNUC_PREREQ #define DEMANGLE_GNUC_PREREQ ( maj , min , patch  ) Value: 0 Definition at line 46 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_BEGIN #define DEMANGLE_NAMESPACE_BEGIN   namespace llvm { namespace itanium_demangle { Definition at line 97 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_END #define DEMANGLE_NAMESPACE_END   } } Definition at line 98 of file DemangleConfig.h . ◆  DEMANGLE_UNREACHABLE #define DEMANGLE_UNREACHABLE Definition at line 61 of file DemangleConfig.h . Referenced by demanglePointerCVQualifiers() , ExpandedSpecialSubstitution::getBaseName() , and AbstractManglingParser< Derived, Alloc >::parseExpr() . Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://github.com/yangshun/front-end-interview-handbook/edit/main/contents/companies/palantir-front-end-interview-questions.md | Sign in to GitHub · GitHub Skip to content You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert Sign in to GitHub {{ message }} --> Username or email address Password Forgot password? Uh oh! There was an error while loading. Please reload this page . New to GitHub? Create an account Sign in with a passkey Terms Privacy Docs Contact GitHub Support Manage cookies Do not share my personal information You can’t perform that action at this time. | 2026-01-13T09:30:39 |
https://www.timeforkids.com/k1/topics/science/ | TIME for Kids | Science | Topic | K-1 Skip to main content Search Articles by Grade level Grades K-1 Articles Grade 2 Articles Grades 3-4 Articles Grades 5-6 Articles Topics Animals Arts Ask Angela Books Business Careers Community Culture Debate Earth Science Education Election 2024 Engineering Environment Food and Nutrition Games Government History Holidays Inventions Movies and Television Music and Theater Nature News People Places Podcasts Science Service Stars Space Sports The Human Body The View Transportation Weather World Young Game Changers Your $ Financial Literacy Content Grade 4 Edition Grade 5-6 Edition For Grown-ups Resource Spotlight Also from TIME for Kids: Log In role: none user_age: none editions: The page you are about to enter is for grown-ups. Enter your birth date to continue. Month (MM) 01 02 03 04 05 06 07 08 09 10 11 12 Year (YYYY) 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 Submit Science Environment We Need Trees March 14, 2025 Take a look outside. Do you see any trees? They are an important natural resource. Trees help the environment. They give us clean air to breathe. Read about other ways that trees benefit people and the planet. Trees shelter animals.… Audio Spanish Environment Celebrate Arbor Day March 14, 2025 Arbor Day is a day to plant trees. The holiday was started by a man named Julius Sterling Morton. He knew that trees are important. He wanted people to plant them for the future. The first Arbor Day was on… Audio Animals Cave Living February 5, 2025 Caves are full of interesting animals. These animals fly, swim, and slither. Here are four cave creatures. Learn how they have adapted to their dark habitat. Bats Bats make a high-pitched sound. It bounces off cave walls. Bats use… Audio Spanish Animals Natural Partners February 5, 2025 Some animals adapt to work together. This is called mutualism. They help each other survive. Read about two examples. Clown Fish and Sea Anemones Sea anemones (above) have tentacles. They sting. But clown fish are not harmed. The fish bring… Audio Animals Grow, Frog, Grow! January 31, 2025 A frog goes through four stages of life. These stages are its life cycle. It looks different at each stage. This change is called metamorphosis. Here is how a frog grows. Egg Female frogs lay hundreds of eggs. The… Audio Spanish Animals Complete Changes January 31, 2025 Some insects go through complete metamorphosis. They change form. Here are three examples. Bees Many bees make cocoons (above). Young bees are called larvas. They are wormlike. They spin a cocoon, like in the photo above. They spend a week… Audio Animals Young Animals January 24, 2025 Baby animals look similar to their parents. But they are smaller. And they have different names. Do you know any of these names? Here are some examples. A baby rabbit is called a kit or kitten. A mother rabbit can… Audio Spanish Animals Natural Partners December 15, 2023 Animals benefit from working together. Plants and animals help one another too. This is called mutualism. Each species provides a service. Each helps the other survive. Read about some helpful relationships. Impalas and Oxpeckers Impalas are bitten by bugs. But… Audio Spanish Animals Animal Friends December 15, 2023 Scientists say friendships help us stay healthy. That’s true for animals too. Unusual Pair (above) Animals can have friends from other species. Dogs and cats are very different but can get along. Cleaning Up These chimpanzees know how to… Audio Environment Explore a Coral Reef April 20, 2023 Many underwater plants and animals live in a coral reef. They depend on the reef for food and protection. People benefit from the reefs, too. Dive in to learn more about coral reefs. Curious Creatures Corals are animals. They… Audio Spanish Posts pagination 1 2 Next Contact us Privacy policy California privacy Terms of Service Subscribe CLASSROOM INTERNATIONAL © 2026 TIME USA, LLC. All Rights Reserved. Powered by WordPress.com VIP | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNodeArray.html#pub-methods | LLVM: NodeArray Class Reference LLVM  22.0.0git Public Member Functions | List of all members NodeArray Class Reference #include " llvm/Demangle/ItaniumDemangle.h " Public Member Functions   NodeArray ()   NodeArray ( Node **Elements_, size_t NumElements_) bool   empty () const size_t  size () const Node **  begin () const Node **  end () const Node *  operator[] (size_t Idx) const void  printWithComma ( OutputBuffer &OB) const bool   printAsString ( OutputBuffer &OB) const Detailed Description Definition at line 327 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  NodeArray() [1/2] NodeArray::NodeArray ( ) inline Definition at line 332 of file ItaniumDemangle.h . ◆  NodeArray() [2/2] NodeArray::NodeArray ( Node ** Elements_ , size_t NumElements_  ) inline Definition at line 333 of file ItaniumDemangle.h . Member Function Documentation ◆  begin() Node ** NodeArray::begin ( ) const inline Definition at line 339 of file ItaniumDemangle.h . ◆  empty() bool NodeArray::empty ( ) const inline Definition at line 336 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseUnnamedTypeName() . ◆  end() Node ** NodeArray::end ( ) const inline Definition at line 340 of file ItaniumDemangle.h . ◆  operator[]() Node * NodeArray::operator[] ( size_t Idx ) const inline Definition at line 342 of file ItaniumDemangle.h . ◆  printAsString() bool NodeArray::printAsString ( OutputBuffer & OB ) const inline Definition at line 2658 of file ItaniumDemangle.h . References Fail , and Node::getKind() . ◆  printWithComma() void NodeArray::printWithComma ( OutputBuffer & OB ) const inline Definition at line 344 of file ItaniumDemangle.h . References Node::Comma . Referenced by llvm::ItaniumPartialDemangler::getFunctionParameters() . ◆  size() size_t NodeArray::size ( ) const inline Definition at line 337 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseExpr() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://lists.llvm.org/pipermail/llvm-dev/2006-December/author.html#7550 | The llvm-dev December 2006 Archive by author December 2006 Archives by author Messages sorted by: [ thread ] [ subject ] [ date ] More info on this list... Starting: Fri Dec 1 02:41:28 PST 2006 Ending: Sun Dec 31 13:37:09 PST 2006 Messages: 245 [LLVMdev] Changing pointer representation? Vikram S. Adve [LLVMdev] Fwd: Compiler opportunities at Cray Vikram S. Adve [LLVMdev] Fwd: Compiler opportunities at Cray Vikram S. Adve [LLVMdev] Removing DSA from LLVM Vikram Sadanand Adve [LLVMdev] LLVM Conference 2007 ? Owen Anderson [LLVMdev] Building llvm-gcc4 on amd64 Domagoj Babic [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Domagoj Babic [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Domagoj Babic [LLVMdev] Building llvm-gcc4 on amd64 Domagoj Babic [LLVMdev] problem building gcc4 front end on fedora core 5 Ram Bhamidipaty [LLVMdev] problem building gcc4 front end on fedora core 5 Ram Bhamidipaty [LLVMdev] jit with external functions Ram Bhamidipaty [LLVMdev] jit with external functions Ram Bhamidipaty [LLVMdev] jit with external functions Ram Bhamidipaty [LLVMdev] No crt2.o file found Matthew Bromberg [LLVMdev] No crt2.o file found Matthew Bromberg [LLVMdev] No crt2.o file found Matthew Bromberg [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Chandler Carruth [LLVMdev] Building llvm-gcc4 on amd64 Chandler Carruth [LLVMdev] Instruction sets requiring more than 3 operands Evan Cheng [LLVMdev] Post-increments and pre-decrements Evan Cheng [LLVMdev] alias-aware scheduling Evan Cheng [LLVMdev] alias-aware scheduling Evan Cheng [LLVMdev] Soft-float Evan Cheng [LLVMdev] Soft-float Evan Cheng [LLVMdev] Instruction sets requiring more than 3 operands Evan Cheng [LLVMdev] nightly tester grawp Evan Cheng [LLVMdev] ThisCall / Compilation problems Jeff Cohen [LLVMdev] Books, papers and information Jeff Cohen [LLVMdev] invalid bytecode signature Ralph Corderoy [LLVMdev] llvm build not respecting DESTDIR? Ralph Corderoy [LLVMdev] LLVM capability question. Ralph Corderoy [LLVMdev] getting process memory info Ralph Corderoy [LLVMdev] Removing DSA from LLVM John Criswell [LLVMdev] #include <iostream> John Criswell [LLVMdev] Potential LLVM Service Outages John Criswell [LLVMdev] More LLVM Mail Server Downtime John Criswell [LLVMdev] DSA Removed John Criswell [LLVMdev] combined arm patch Rafael Espíndola [LLVMdev] combined arm patch Rafael Espíndola [LLVMdev] [llvm-commits] combined arm patch Rafael Espíndola [LLVMdev] weak linkage Rafael Espíndola [LLVMdev] arm patch 1/n Rafael Espíndola [LLVMdev] arm patch 2/n Rafael Espíndola [LLVMdev] arm patch 3/n Rafael Espíndola [LLVMdev] [llvm-commits] combined arm patch Rafael Espíndola [LLVMdev] [llvm-commits] combined arm patch Rafael Espíndola [LLVMdev] weak linkage Rafael Espíndola [LLVMdev] MachineConstantPoolValue Rafael Espíndola [LLVMdev] [patch] print ".weak" directive Rafael Espíndola [LLVMdev] MachineConstantPoolValue Rafael Espíndola [LLVMdev] [patch] print ".weak" directive Rafael Espíndola [LLVMdev] [PATCH] print .weak directives Rafael Espíndola [LLVMdev] [PATCH] print .weak directives Rafael Espíndola [LLVMdev] [patch] emit .weak for zero initialized weak variables Rafael Espíndola [LLVMdev] [patch] move ExtWeakSymbols to AsmPrinter Rafael Espíndola [LLVMdev] [patch] move ExtWeakSymbols to AsmPrinter Rafael Espíndola [LLVMdev] [patch] move ExtWeakSymbols to AsmPrinter Rafael Espíndola [LLVMdev] problems with the legalizer Rafael Espíndola [LLVMdev] [patch] emit .weak for zero initialized weak variables Rafael Espíndola [LLVMdev] [patch] emit .weak for zero initialized weak variables Rafael Espíndola [LLVMdev] [patch] emit .weak for zero initialized weak variables Rafael Espíndola [LLVMdev] alias-aware scheduling Dan Gohman [LLVMdev] alias-aware scheduling Dan Gohman [LLVMdev] Changing pointer representation? Jules [LLVMdev] Instructions having variable names as operands Nikolaos Kavvadias [LLVMdev] MachineConstantPoolValue Anton Korobeynikov [LLVMdev] ThisCall / Compilation problems Anton Korobeynikov [LLVMdev] No crt2.o file found Anton Korobeynikov [LLVMdev] Building Qt with LLVM Anton Korobeynikov [LLVMdev] No crt2.o file found Anton Korobeynikov [LLVMdev] No crt2.o file found Anton Korobeynikov [LLVMdev] No crt2.o file found Anton Korobeynikov [LLVMdev] No crt2.o file found Anton Korobeynikov [LLVMdev] combined arm patch Jim Laskey [LLVMdev] problem building gcc4 front end on fedora core 5 Jim Laskey [LLVMdev] combined arm patch Jim Laskey [LLVMdev] combined arm patch Jim Laskey [LLVMdev] combined arm patch Jim Laskey [LLVMdev] [llvm-commits] combined arm patch Jim Laskey [LLVMdev] [llvm-commits] combined arm patch Jim Laskey [LLVMdev] MachineFunction.cpp!!! Jim Laskey [LLVMdev] nightly tester grawp Jim Laskey [LLVMdev] Changing pointer representation? Chris Lattner [LLVMdev] Disable Inlining Chris Lattner [LLVMdev] crtend Chris Lattner [LLVMdev] invalid bytecode signature Chris Lattner [LLVMdev] timer mem stats not implemented? Chris Lattner [LLVMdev] # operands < # args Chris Lattner [LLVMdev] problem using scc_iterator on CallGraph Chris Lattner [LLVMdev] possible bug in X86TargetLowering::getRegClassForInlineAsmConstraint Chris Lattner [LLVMdev] Fwd: Compiler opportunities at Cray Chris Lattner [LLVMdev] weak linkage Chris Lattner [LLVMdev] #include <iostream> Chris Lattner [LLVMdev] Proposed: first class packed structures Chris Lattner [LLVMdev] [patch] print ".weak" directive Chris Lattner [LLVMdev] MachineConstantPoolValue Chris Lattner [LLVMdev] Proposed: first class packed structures Chris Lattner [LLVMdev] Proposed: first class packed structures Chris Lattner [LLVMdev] #include <iostream> Chris Lattner [LLVMdev] Proposed: first class packed structures Chris Lattner [LLVMdev] Removing DSA from LLVM Chris Lattner [LLVMdev] jit with external functions Chris Lattner [LLVMdev] jit with external functions Chris Lattner [LLVMdev] [PATCH] print .weak directives Chris Lattner [LLVMdev] Building llvm-gcc4 on amd64 Chris Lattner [LLVMdev] [patch] move ExtWeakSymbols to AsmPrinter Chris Lattner [LLVMdev] [PATCH] print .weak directives Chris Lattner [LLVMdev] problem using scc_iterator on CallGraph Chris Lattner [LLVMdev] DSA Removed Chris Lattner [LLVMdev] problems with the legalizer Chris Lattner [LLVMdev] Instructions having variable names as operands Chris Lattner [LLVMdev] [patch] move ExtWeakSymbols to AsmPrinter Chris Lattner [LLVMdev] [patch] emit .weak for zero initialized weak variables Chris Lattner [LLVMdev] Building Qt with LLVM Chris Lattner [LLVMdev] [patch] emit .weak for zero initialized weak variables Chris Lattner [LLVMdev] Statistic API change Chris Lattner [LLVMdev] alias-aware scheduling Chris Lattner [LLVMdev] Books, papers and information Chris Lattner [LLVMdev] Instructions having variable names as operands Chris Lattner [LLVMdev] Instructions having variable names as operands Chris Lattner [LLVMdev] Soft-float Chris Lattner [LLVMdev] LLVM capability question. Chris Lattner [LLVMdev] [patch] arm: external weak in constant pool Chris Lattner [LLVMdev] [patch] arm: define extloadi1 Chris Lattner [LLVMdev] Possible bug in the linear scan register allocator Chris Lattner [LLVMdev] in Cygwin problems Chris Lattner [LLVMdev] Possible bug in the linear scan register allocator Chris Lattner [LLVMdev] nightly tester grawp Chris Lattner [LLVMdev] nightly tester grawp Chris Lattner [LLVMdev] llvm-gcc frontend 4 on intel darwin produces intel assembler Tanya M. Lattner [LLVMdev] in Cygwin problems Tanya M. Lattner [LLVMdev] in Cygwin problems Tanya M. Lattner [LLVMdev] Instruction sets requiring more than 3 operands Seung Jae Lee [LLVMdev] Instructions having variable names as operands Seung Jae Lee [LLVMdev] Instruction sets requiring more than 3 operands Seung Jae Lee [LLVMdev] Instructions having variable names as operands Seung Jae Lee [LLVMdev] Instructions having variable names as operands Seung Jae Lee [LLVMdev] Disable Inlining Ryan M. Lefever [LLVMdev] crtend Ryan M. Lefever [LLVMdev] invalid bytecode signature Ryan M. Lefever [LLVMdev] invalid bytecode signature Ryan M. Lefever [LLVMdev] weird analysis group behavior Ryan M. Lefever [LLVMdev] timer mem stats not implemented? Ryan M. Lefever [LLVMdev] # operands < # args Ryan M. Lefever [LLVMdev] problem using scc_iterator on CallGraph Ryan M. Lefever [LLVMdev] problem using scc_iterator on CallGraph Ryan M. Lefever [LLVMdev] Removing DSA from LLVM Ryan M. Lefever [LLVMdev] post-dominance frontier Ryan M. Lefever [LLVMdev] DSGraph::computeCalleeCallerMapping failing Andrew Lenharth [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] Bytecode change Andrew Lenharth [LLVMdev] [patch] llvm-gcc support for packed structures Andrew Lenharth [LLVMdev] Post-increments and pre-decrements Roman Levenstein [LLVMdev] Problems with new bytecode format Roman Levenstein [LLVMdev] Problems with new bytecode format Roman Levenstein [LLVMdev] Soft-float Roman Levenstein [LLVMdev] Memory protection using run-time checks Roman Levenstein [LLVMdev] Soft-float Roman Levenstein [LLVMdev] Possible bug in the linear scan register allocator Roman Levenstein [LLVMdev] Possible bug in the linear scan register allocator Roman Levenstein [LLVMdev] nightly tester grawp Nick Lewycky [LLVMdev] Sparse and LLVM Chris Li [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Scott Michel [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Scott Michel [LLVMdev] moving to svn? Chris Morgan [LLVMdev] EH and C++ integration Žiga Osolin [LLVMdev] Full C++ support Žiga Osolin [LLVMdev] ThisCall / Compilation problems Žiga Osolin [LLVMdev] New PassManager Devang Patel [LLVMdev] nightly tester grawp Devang Patel [LLVMdev] llvm-gcc frontend 4 on intel darwin produces intel assembler Jakob Praher [LLVMdev] llvm-gcc frontend 4 on intel darwin produces intel assembler Jakob Praher [LLVMdev] getting process memory info Jakob Praher [LLVMdev] getting process memory info Jakob Praher [LLVMdev] #include <iostream> Vladimir Prus [LLVMdev] Books, papers and information Ramana Radhakrishnan [LLVMdev] LLVM capability question. Michael T. Richter [LLVMdev] in Cygwin problems Roman [LLVMdev] in Cygwin problems Roman [LLVMdev] in Cygwin problems Roman [LLVMdev] in Cygwin problems Roman [LLVMdev] in Cygwin problems Roman [LLVMdev] DSGraph::computeCalleeCallerMapping failing Swarup Kumar Sahoo [LLVMdev] DSGraph::computeCalleeCallerMapping failing Swarup Kumar Sahoo [LLVMdev] Sparse and LLVM Sanghyeon Seo [LLVMdev] No crt2.o file found SevenThunders [LLVMdev] ThisCall / Compilation problems David Shipman [LLVMdev] invalid bytecode signature Reid Spencer [LLVMdev] problem building gcc4 front end on fedora core 5 Reid Spencer [LLVMdev] Reminder: LLVM Conference 2007 Poll Reid Spencer [LLVMdev] Dropping support for llvm-gcc3 Reid Spencer [LLVMdev] Full C++ support Reid Spencer [LLVMdev] llc doesn't work in release build Reid Spencer [LLVMdev] Proposed: first class packed structures Reid Spencer [LLVMdev] llvm build not respecting DESTDIR? Reid Spencer [LLVMdev] llvm build not respecting DESTDIR? Reid Spencer [LLVMdev] llvm build not respecting DESTDIR? Reid Spencer [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Reid Spencer [LLVMdev] Reminder: LLVM Conference 2007 Reid Spencer [LLVMdev] ThisCall / Compilation problems Reid Spencer [LLVMdev] Books, papers and information Reid Spencer [LLVMdev] Problems with new bytecode format Reid Spencer [LLVMdev] Problems with new bytecode format Reid Spencer [LLVMdev] Building llvm-gcc4 Reid Spencer [LLVMdev] lli, llvm-ld and runtime libraries Reid Spencer [LLVMdev] LLVM capability question. Reid Spencer [LLVMdev] in Cygwin problems Reid Spencer [LLVMdev] Sparse and LLVM Reid Spencer [LLVMdev] nightly tester grawp Reid Spencer [LLVMdev] nightly tester grawp Reid Spencer [LLVMdev] nightly tester grawp Reid Spencer [LLVMdev] nightly tester grawp Reid Spencer [LLVMdev] nightly tester grawp Reid Spencer [LLVMdev] Books, papers and information Fredrik Svensson [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] lli, llvm-ld and runtime libraries Erick Tryzelaar [LLVMdev] llc doesn't work in release build Anton Vayvod [LLVMdev] possible bug in X86TargetLowering::getRegClassForInlineAsmConstraint Lauro Ramos Venancio [LLVMdev] [patch] getRegClassForInlineAsmConstraint for ARM Lauro Ramos Venancio [LLVMdev] [patch] getRegClassForInlineAsmConstraint for ARM Lauro Ramos Venancio [LLVMdev] [patch] arm bugfix: invalid add/sub constant Lauro Ramos Venancio [LLVMdev] [patch] arm: external weak in constant pool Lauro Ramos Venancio [LLVMdev] [patch] arm: external weak in constant pool Lauro Ramos Venancio [LLVMdev] [patch] arm: define extloadi1 Lauro Ramos Venancio [LLVMdev] #include <iostream> Bill Wendling [LLVMdev] #include <iostream> Bill Wendling [LLVMdev] #include <iostream> Bill Wendling [LLVMdev] #include <iostream> Bill Wendling [LLVMdev] MachineFunction.cpp!!! Bill Wendling [LLVMdev] ThisCall / Compilation problems Bill Wendling [LLVMdev] Problems with new bytecode format Bill Wendling [LLVMdev] [patch] arm: external weak in constant pool Bill Wendling [LLVMdev] Books, papers and information Zhongxing Xu [LLVMdev] -s- sriram at malhar.net Last message date: Sun Dec 31 13:37:09 PST 2006 Archived on: Tue Aug 4 17:22:51 PDT 2015 Messages sorted by: [ thread ] [ subject ] [ date ] More info on this list... This archive was generated by Pipermail 0.09 (Mailman edition). | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Exercise:-Function-plots | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://www.php.net/manual/zh/function.tidy-warning-count.php | PHP: tidy_warning_count - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box Tokenizer » « tidy_get_output PHP 手册 函数参考 其它基本扩展 Tidy Tidy 函数 切换语言: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other tidy_warning_count (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document 说明 tidy_warning_count ( tidy $tidy ): int Returns the number of Tidy warnings encountered for the specified document. 参数 tidy The Tidy 对象。 返回值 Returns the number of warnings. 示例 示例 #1 tidy_warning_count() example <?php $html = '<p>test</i> <bogustag>bogus</bogustag>' ; $tidy = tidy_parse_string ( $html ); echo tidy_error_count ( $tidy ) . "\n" ; //1 echo tidy_warning_count ( $tidy ) . "\n" ; //5 ?> 参见 tidy_error_count() - Returns the Number of Tidy errors encountered for specified document tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document 发现了问题? 了解如何改进此页面 • 提交拉取请求 • 报告一个错误 + 添加备注 用户贡献的备注 此页面尚无用户贡献的备注。 Tidy 函数 ob_​tidyhandler tidy_​access_​count tidy_​config_​count tidy_​error_​count tidy_​get_​output tidy_​warning_​count Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://t.me/share/url?url= | Telegram Messenger English Bahasa Indonesia Bahasa Melayu Deutsch Español Français Italiano Nederlands O‘zbek Polski Português (Brasil) Türkçe Беларуская Русский Українська Қазақша العربية فارسی 한국어 Twitter Home FAQ Apps API Moderation Recent News Jan 3 AI Summaries, New Design and More Dec 12 Passkeys, Gift Purchase Offers and More Nov 19 Live Stories, Repeated Messages, Auctions for Gifts and More a new era of messaging Telegram for Android Telegram for iPhone / iPad Telegram for Windows / Mac / Linux Browse more Telegram apps Telegram for PC / Linux Telegram for macOS Recent News AI Summaries, New Design and More Telegram's first update of 2026 brings even more Liquid Glass interfaces on iOS and AI summaries for channel posts and Instant View pages — built to maximize privacy and protect user… Jan 3, 2026 Passkeys, Gift Purchase Offers and More In today's update, we add secure passkeys for instant login without SMS codes, gift purchase offers with built-in scam protection, and a simple way to add audio from your profile to… Dec 12, 2025 Why Telegram? Simple Telegram is so simple you already know how to use it. Private Telegram messages are heavily encrypted and can self-destruct. Synced Telegram lets you access your chats from multiple devices. Fast Telegram delivers messages faster than any other application. Powerful Telegram has no limits on the size of your media and chats. Open Telegram has an open API and source code free for everyone. Secure Telegram keeps your messages safe from hacker attacks. Social Telegram groups can hold up to 200,000 members. Expressive Telegram lets you completely customize your messenger. Telegram Telegram is a cloud-based mobile and desktop messaging app with a focus on security and speed. About FAQ Privacy Press Mobile Apps iPhone/iPad Android Mobile Web Desktop Apps PC/Mac/Linux macOS Web-browser Platform API Translations Instant View About Blog Press Moderation | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNode.html#a1741d927ae4f746a135ec7557c5f8a8ca074de7e7c226d5c60f8af14c20725352 | LLVM: Node Class Reference LLVM  22.0.0git Public Types | Public Member Functions | Protected Attributes | Friends | List of all members Node Class Reference abstract #include " llvm/Demangle/ItaniumDemangle.h " Inherited by FloatLiteralImpl< float > , FloatLiteralImpl< double > , FloatLiteralImpl< long double > , AbiTagAttr , ArraySubscriptExpr , ArrayType , BinaryExpr , BinaryFPType , BitIntType , BoolExpr , BracedExpr , BracedRangeExpr , CallExpr , CastExpr , ClosureTypeName , ConditionalExpr , ConstrainedTypeTemplateParamDecl , ConversionExpr , ConversionOperatorType , CtorDtorName , CtorVtableSpecialName , DeleteExpr , DotSuffix , DtorName , DynamicExceptionSpec , ElaboratedTypeSpefType , EnableIfAttr , EnclosingExpr , EnumLiteral , ExpandedSpecialSubstitution , ExplicitObjectParameter , ExprRequirement , FloatLiteralImpl< Float > , FoldExpr , ForwardTemplateReference , FunctionEncoding , FunctionParam , FunctionType , GlobalQualifiedName , InitListExpr , IntegerLiteral , LambdaExpr , LiteralOperator , LocalName , MemberExpr , MemberLikeFriendName , ModuleEntity , ModuleName , NameType , NameWithTemplateArgs , NestedName , NestedRequirement , NewExpr , NodeArrayNode , NoexceptSpec , NonTypeTemplateParamDecl , ObjCProtoName , ParameterPack , ParameterPackExpansion , PixelVectorType , PointerToMemberConversionExpr , PointerToMemberType , PointerType , PostfixExpr , PostfixQualifiedType , PrefixExpr , QualType , QualifiedName , ReferenceType , RequiresExpr , SizeofParamPackExpr , SpecialName , StringLiteral , StructuredBindingName , SubobjectExpr , SyntheticTemplateParamName , TemplateArgs , TemplateArgumentPack , TemplateParamPackDecl , TemplateParamQualifiedArg , TemplateTemplateParamDecl , ThrowExpr , TransformedType , TypeRequirement , TypeTemplateParamDecl , UnnamedTypeName , VectorType , and VendorExtQualType . Public Types enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Public Member Functions   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Protected Attributes Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Friends class  OutputBuffer Detailed Description Definition at line 166 of file ItaniumDemangle.h . Member Enumeration Documentation ◆  Cache enum class Node::Cache : uint8_t strong Three-way bool to track a cached value. Unknown is possible if this node has an unexpanded parameter pack below it that may affect this cache. Enumerator Yes  No  Unknown  Definition at line 175 of file ItaniumDemangle.h . ◆  Kind enum Node::Kind : uint8_t Definition at line 168 of file ItaniumDemangle.h . ◆  Prec enum class Node::Prec : uint8_t strong Operator precedence for expression nodes. Used to determine required parens in expression emission. Enumerator Primary  Postfix  Unary  Cast  PtrMem  Multiplicative  Additive  Shift  Spaceship  Relational  Equality  And  Xor  Ior  AndIf  OrIf  Conditional  Assign  Comma  Default  Definition at line 179 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  Node() [1/2] Node::Node ( Kind K_ , Prec Precedence_ = Prec::Primary , Cache RHSComponentCache_ = Cache::No , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 221 of file ItaniumDemangle.h . References ArrayCache , FunctionCache , No , Primary , and RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , ArraySubscriptExpr::ArraySubscriptExpr() , ArrayType::ArrayType() , BinaryExpr::BinaryExpr() , BinaryFPType::BinaryFPType() , BitIntType::BitIntType() , BoolExpr::BoolExpr() , BracedExpr::BracedExpr() , BracedRangeExpr::BracedRangeExpr() , CallExpr::CallExpr() , CastExpr::CastExpr() , ClosureTypeName::ClosureTypeName() , ConditionalExpr::ConditionalExpr() , ConstrainedTypeTemplateParamDecl::ConstrainedTypeTemplateParamDecl() , ConversionExpr::ConversionExpr() , ConversionOperatorType::ConversionOperatorType() , CtorDtorName::CtorDtorName() , CtorVtableSpecialName::CtorVtableSpecialName() , DeleteExpr::DeleteExpr() , DotSuffix::DotSuffix() , DtorName::DtorName() , DynamicExceptionSpec::DynamicExceptionSpec() , ElaboratedTypeSpefType::ElaboratedTypeSpefType() , EnableIfAttr::EnableIfAttr() , EnclosingExpr::EnclosingExpr() , EnumLiteral::EnumLiteral() , ExpandedSpecialSubstitution::ExpandedSpecialSubstitution() , ExplicitObjectParameter::ExplicitObjectParameter() , ExprRequirement::ExprRequirement() , FloatLiteralImpl< float >::FloatLiteralImpl() , FoldExpr::FoldExpr() , ForwardTemplateReference::ForwardTemplateReference() , FunctionEncoding::FunctionEncoding() , FunctionParam::FunctionParam() , FunctionType::FunctionType() , TemplateParamQualifiedArg::getArg() , FunctionEncoding::getAttrs() , VectorType::getBaseType() , ParameterPackExpansion::getChild() , QualType::getChild() , VectorType::getDimension() , FunctionEncoding::getName() , PointerType::getPointee() , FunctionEncoding::getRequires() , FunctionEncoding::getReturnType() , ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , VendorExtQualType::getTA() , VendorExtQualType::getTy() , GlobalQualifiedName::GlobalQualifiedName() , InitListExpr::InitListExpr() , IntegerLiteral::IntegerLiteral() , LambdaExpr::LambdaExpr() , LiteralOperator::LiteralOperator() , LocalName::LocalName() , MemberExpr::MemberExpr() , MemberLikeFriendName::MemberLikeFriendName() , ModuleEntity::ModuleEntity() , ModuleName::ModuleName() , NameType::NameType() , NameWithTemplateArgs::NameWithTemplateArgs() , NestedName::NestedName() , NestedRequirement::NestedRequirement() , NewExpr::NewExpr() , Node() , NodeArrayNode::NodeArrayNode() , NoexceptSpec::NoexceptSpec() , NonTypeTemplateParamDecl::NonTypeTemplateParamDecl() , ObjCProtoName::ObjCProtoName() , ParameterPack::ParameterPack() , ParameterPackExpansion::ParameterPackExpansion() , PixelVectorType::PixelVectorType() , PointerToMemberConversionExpr::PointerToMemberConversionExpr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , PostfixExpr::PostfixExpr() , PostfixQualifiedType::PostfixQualifiedType() , PrefixExpr::PrefixExpr() , RequiresExpr::printLeft() , QualifiedName::QualifiedName() , QualType::QualType() , ReferenceType::ReferenceType() , RequiresExpr::RequiresExpr() , SizeofParamPackExpr::SizeofParamPackExpr() , SpecialName::SpecialName() , StringLiteral::StringLiteral() , StructuredBindingName::StructuredBindingName() , SubobjectExpr::SubobjectExpr() , SyntheticTemplateParamName::SyntheticTemplateParamName() , TemplateArgs::TemplateArgs() , TemplateArgumentPack::TemplateArgumentPack() , TemplateParamPackDecl::TemplateParamPackDecl() , TemplateParamQualifiedArg::TemplateParamQualifiedArg() , TemplateTemplateParamDecl::TemplateTemplateParamDecl() , ThrowExpr::ThrowExpr() , TransformedType::TransformedType() , TypeRequirement::TypeRequirement() , TypeTemplateParamDecl::TypeTemplateParamDecl() , UnnamedTypeName::UnnamedTypeName() , VectorType::VectorType() , and VendorExtQualType::VendorExtQualType() . ◆  Node() [2/2] Node::Node ( Kind K_ , Cache RHSComponentCache_ , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 226 of file ItaniumDemangle.h . References No , Node() , and Primary . ◆  ~Node() virtual Node::~Node ( ) virtual default Member Function Documentation ◆  dump() DEMANGLE_DUMP_METHOD void Node::dump ( ) const References DEMANGLE_DUMP_METHOD . Referenced by llvm::DAGTypeLegalizer::run() , and llvm::RISCVDAGToDAGISel::Select() . ◆  getArrayCache() Cache Node::getArrayCache ( ) const inline Definition at line 262 of file ItaniumDemangle.h . References ArrayCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getBaseName() virtual std::string_view Node::getBaseName ( ) const inline virtual Reimplemented in AbiTagAttr , ExpandedSpecialSubstitution , GlobalQualifiedName , MemberLikeFriendName , ModuleEntity , NameType , NameWithTemplateArgs , NestedName , QualifiedName , and SpecialSubstitution . Definition at line 299 of file ItaniumDemangle.h . ◆  getFunctionCache() Cache Node::getFunctionCache ( ) const inline Definition at line 263 of file ItaniumDemangle.h . References FunctionCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getKind() Kind Node::getKind ( ) const inline Definition at line 258 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseCtorDtorName() , AbstractManglingParser< Derived, Alloc >::parseNestedName() , AbstractManglingParser< Derived, Alloc >::parseTemplateArgs() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnscopedName() , NodeArray::printAsString() , and llvm::msgpack::Document::writeToBlob() . ◆  getPrecedence() Prec Node::getPrecedence ( ) const inline Definition at line 260 of file ItaniumDemangle.h . Referenced by ArraySubscriptExpr::match() , BinaryExpr::match() , CallExpr::match() , CastExpr::match() , ConditionalExpr::match() , ConversionExpr::match() , DeleteExpr::match() , EnclosingExpr::match() , MemberExpr::match() , NewExpr::match() , PointerToMemberConversionExpr::match() , PostfixExpr::match() , PrefixExpr::match() , printAsOperand() , ArraySubscriptExpr::printLeft() , BinaryExpr::printLeft() , ConditionalExpr::printLeft() , MemberExpr::printLeft() , PostfixExpr::printLeft() , and PrefixExpr::printLeft() . ◆  getRHSComponentCache() Cache Node::getRHSComponentCache ( ) const inline Definition at line 261 of file ItaniumDemangle.h . References RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , QualType::QualType() , and ReferenceType::ReferenceType() . ◆  getSyntaxNode() virtual const Node * Node::getSyntaxNode ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , and ParameterPack . Definition at line 271 of file ItaniumDemangle.h . References Node() , and OutputBuffer . ◆  hasArray() bool Node::hasArray ( OutputBuffer & OB ) const inline Definition at line 246 of file ItaniumDemangle.h . References ArrayCache , hasArraySlow() , OutputBuffer , Unknown , and Yes . ◆  hasArraySlow() virtual bool Node::hasArraySlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , ParameterPack , and QualType . Definition at line 266 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasArray() . ◆  hasFunction() bool Node::hasFunction ( OutputBuffer & OB ) const inline Definition at line 252 of file ItaniumDemangle.h . References FunctionCache , hasFunctionSlow() , OutputBuffer , Unknown , and Yes . ◆  hasFunctionSlow() virtual bool Node::hasFunctionSlow ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , and QualType . Definition at line 267 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasFunction() . ◆  hasRHSComponent() bool Node::hasRHSComponent ( OutputBuffer & OB ) const inline Definition at line 240 of file ItaniumDemangle.h . References hasRHSComponentSlow() , OutputBuffer , RHSComponentCache , Unknown , and Yes . ◆  hasRHSComponentSlow() virtual bool Node::hasRHSComponentSlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , PointerToMemberType , PointerType , QualType , and ReferenceType . Definition at line 265 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasRHSComponent() . ◆  print() void Node::print ( OutputBuffer & OB ) const inline Definition at line 286 of file ItaniumDemangle.h . References No , OutputBuffer , and RHSComponentCache . Referenced by llvm::ItaniumPartialDemangler::getFunctionDeclContextName() , llvm::DOTGraphTraits< AADepGraph * >::getNodeLabel() , llvm::DOTGraphTraits< const MachineFunction * >::getNodeLabel() , llvm::itaniumDemangle() , printAsOperand() , FoldExpr::printLeft() , and printNode() . ◆  printAsOperand() void Node::printAsOperand ( OutputBuffer & OB , Prec P = Prec::Default , bool StrictlyWorse = false  ) const inline Definition at line 275 of file ItaniumDemangle.h . References Default , getPrecedence() , OutputBuffer , P , and print() . Referenced by llvm::DOTGraphTraits< DOTFuncInfo * >::getBBName() , getSimpleNodeName() , llvm::operator<<() , llvm::VPIRMetadata::print() , and llvm::SimpleNodeLabelString() . ◆  printInitListAsType() virtual bool Node::printInitListAsType ( OutputBuffer & , const NodeArray &  ) const inline virtual Reimplemented in ArrayType . Definition at line 295 of file ItaniumDemangle.h . References OutputBuffer . ◆  visit() template<typename Fn> void Node::visit ( Fn F ) const Visit the most-derived object corresponding to this object. Visit the node. Calls F(P) , where P is the node cast to the appropriate derived class. Definition at line 2639 of file ItaniumDemangle.h . References DEMANGLE_ASSERT , and F . Friends And Related Symbol Documentation ◆  OutputBuffer friend class OutputBuffer friend Definition at line 309 of file ItaniumDemangle.h . References OutputBuffer . Referenced by ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , hasArray() , ArrayType::hasArraySlow() , ForwardTemplateReference::hasArraySlow() , hasArraySlow() , ParameterPack::hasArraySlow() , QualType::hasArraySlow() , hasFunction() , ForwardTemplateReference::hasFunctionSlow() , FunctionEncoding::hasFunctionSlow() , FunctionType::hasFunctionSlow() , hasFunctionSlow() , ParameterPack::hasFunctionSlow() , QualType::hasFunctionSlow() , hasRHSComponent() , ArrayType::hasRHSComponentSlow() , ForwardTemplateReference::hasRHSComponentSlow() , FunctionEncoding::hasRHSComponentSlow() , FunctionType::hasRHSComponentSlow() , hasRHSComponentSlow() , ParameterPack::hasRHSComponentSlow() , PointerToMemberType::hasRHSComponentSlow() , PointerType::hasRHSComponentSlow() , QualType::hasRHSComponentSlow() , ReferenceType::hasRHSComponentSlow() , OutputBuffer , print() , printAsOperand() , ClosureTypeName::printDeclarator() , ArrayType::printInitListAsType() , printInitListAsType() , AbiTagAttr::printLeft() , ArraySubscriptExpr::printLeft() , ArrayType::printLeft() , BinaryExpr::printLeft() , BinaryFPType::printLeft() , BitIntType::printLeft() , BoolExpr::printLeft() , BracedExpr::printLeft() , BracedRangeExpr::printLeft() , CallExpr::printLeft() , CastExpr::printLeft() , ClosureTypeName::printLeft() , ConditionalExpr::printLeft() , ConstrainedTypeTemplateParamDecl::printLeft() , ConversionExpr::printLeft() , ConversionOperatorType::printLeft() , CtorDtorName::printLeft() , CtorVtableSpecialName::printLeft() , DeleteExpr::printLeft() , DotSuffix::printLeft() , DtorName::printLeft() , DynamicExceptionSpec::printLeft() , ElaboratedTypeSpefType::printLeft() , EnableIfAttr::printLeft() , EnclosingExpr::printLeft() , EnumLiteral::printLeft() , ExplicitObjectParameter::printLeft() , ExprRequirement::printLeft() , FloatLiteralImpl< float >::printLeft() , FoldExpr::printLeft() , ForwardTemplateReference::printLeft() , FunctionEncoding::printLeft() , FunctionParam::printLeft() , FunctionType::printLeft() , GlobalQualifiedName::printLeft() , InitListExpr::printLeft() , IntegerLiteral::printLeft() , LambdaExpr::printLeft() , LiteralOperator::printLeft() , LocalName::printLeft() , MemberExpr::printLeft() , MemberLikeFriendName::printLeft() , ModuleEntity::printLeft() , ModuleName::printLeft() , NameType::printLeft() , NameWithTemplateArgs::printLeft() , NestedName::printLeft() , NestedRequirement::printLeft() , NewExpr::printLeft() , NodeArrayNode::printLeft() , NoexceptSpec::printLeft() , NonTypeTemplateParamDecl::printLeft() , ObjCProtoName::printLeft() , ParameterPack::printLeft() , ParameterPackExpansion::printLeft() , PixelVectorType::printLeft() , PointerToMemberConversionExpr::printLeft() , PointerToMemberType::printLeft() , PointerType::printLeft() , PostfixExpr::printLeft() , PostfixQualifiedType::printLeft() , PrefixExpr::printLeft() , QualifiedName::printLeft() , QualType::printLeft() , ReferenceType::printLeft() , RequiresExpr::printLeft() , SizeofParamPackExpr::printLeft() , SpecialName::printLeft() , SpecialSubstitution::printLeft() , StringLiteral::printLeft() , StructuredBindingName::printLeft() , SubobjectExpr::printLeft() , SyntheticTemplateParamName::printLeft() , TemplateArgs::printLeft() , TemplateArgumentPack::printLeft() , TemplateParamPackDecl::printLeft() , TemplateParamQualifiedArg::printLeft() , TemplateTemplateParamDecl::printLeft() , ThrowExpr::printLeft() , TransformedType::printLeft() , TypeRequirement::printLeft() , TypeTemplateParamDecl::printLeft() , UnnamedTypeName::printLeft() , VectorType::printLeft() , VendorExtQualType::printLeft() , QualType::printQuals() , ArrayType::printRight() , ConstrainedTypeTemplateParamDecl::printRight() , ForwardTemplateReference::printRight() , FunctionEncoding::printRight() , FunctionType::printRight() , NonTypeTemplateParamDecl::printRight() , ParameterPack::printRight() , PointerToMemberType::printRight() , PointerType::printRight() , QualType::printRight() , ReferenceType::printRight() , TemplateParamPackDecl::printRight() , TemplateTemplateParamDecl::printRight() , and TypeTemplateParamDecl::printRight() . Member Data Documentation ◆  ArrayCache Cache Node::ArrayCache protected Track if this node is a (possibly qualified) array type. This can affect how we format the output string. Definition at line 214 of file ItaniumDemangle.h . Referenced by getArrayCache() , hasArray() , Node() , and ParameterPack::ParameterPack() . ◆  FunctionCache Cache Node::FunctionCache protected Track if this node is a (possibly qualified) function type. This can affect how we format the output string. Definition at line 218 of file ItaniumDemangle.h . Referenced by getFunctionCache() , hasFunction() , Node() , and ParameterPack::ParameterPack() . ◆  RHSComponentCache Cache Node::RHSComponentCache protected Tracks if this node has a component on its right side, in which case we need to call printRight. Definition at line 210 of file ItaniumDemangle.h . Referenced by getRHSComponentCache() , hasRHSComponent() , Node() , ParameterPack::ParameterPack() , and print() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://www.php.net/manual/uk/function.crc32.php | PHP: crc32 - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box crypt » « count_chars Посібник з PHP Довідник функцій Обробка тексту Strings String Функції Change language: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other crc32 (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) crc32 — Обчислює CRC32-поліном для рядка Опис crc32 ( string $string ): int Функція обчислює циклічний надлишковий код 32-бітних поліномів для рядка string . Зазвичай використовується для перевірки цілісності передачі даних. Увага Оскільки в PHP числа цілого типу мають знак, то багато контрольних сум міститимуть від'ємні значення на 32-розрядних системах. На 64-бітних системах усі результати crc32() матимуть додатні цілі числа. Таким чином ви повинні використовувати форматування типу "%u" разом зі sprintf() або printf() , щоб отримати рядкове представлення crc32() -суми в десятковому форматі без знаку. Для шістнадцяткового представлення контрольної суми ви можете використати форматування типу "%x" разом зі sprintf() чи printf() або ж функцію dechex() . Кожен з цих способів подбає про перетворення результату crc32() у беззнакове ціле число. Для 64-бітних систем також розглядалася можливість повертання від'ємного результату для великих значень, але це б зруйнувало шістнадцяткове перетворення додаючи до нього додаткове 0xFFFFFFFF######## зміщення. Оскільки шістнадцяткове представлення використовується найчастіше, було вирішено залишити його, навіть якщо це порушує пряме порівняння десяткових значень приблизно в 50% випадків при переході з 32 на 64-бітні системи. Оглядаючись назад, функції, які повертають десяткові значення, мабуть, були не найкращою ідеєю, і повернення представлення у вигляді шістнадцяткового рядка (як це реалізовано у md5() ) було б кращим варіантом. Для більшої універсальності ви можете використати функцію hash() . hash("crc32b", $str) поверне такий самий рядок, як і str_pad(dechex(crc32($str)), 8, '0', STR_PAD_LEFT) . Параметри string Дані. Значення, що повертаються Повертає контрольну суму CRC32-рядка string у вигляді цілого числа. Приклади Приклад #1 Відображення контрольної суми CRC32 Цей приклад показує вивід контрольної суми за допомогою функції printf() : <?php $checksum = crc32 ( "І чорна корова біле молоко дає." ); printf ( "%u\n" , $checksum ); // $checksum поверне 1401500516 ?> Прогляньте також hash() - Generate a hash value (message digest) md5() - Обчислює MD5-хеш рядка sha1() - Обчислює SHA1-хеш рядка Found A Problem? Learn How To Improve This Page • Submit a Pull Request • Report a Bug + add a note User Contributed Notes 22 notes up down 24 jian at theorchard dot com ¶ 15 years ago This function returns an unsigned integer from a 64-bit Linux platform. It does return the signed integer from other 32-bit platforms even a 64-bit Windows one. The reason is because the two constants PHP_INT_SIZE and PHP_INT_MAX have different values on the 64-bit Linux platform. I've created a work-around function to handle this situation. <?php function get_signed_int ( $in ) { $int_max = pow ( 2 , 31 )- 1 ; if ( $in > $int_max ){ $out = $in - $int_max * 2 - 2 ; } else { $out = $in ; } return $out ; } ?> Hope this helps. up down 12 i at morfi dot ru ¶ 12 years ago Implementation crc64() in php 64bit <?php /** * @return array */ function crc64Table () { $crc64tab = []; // ECMA polynomial $poly64rev = ( 0xC96C5795 << 32 ) | 0xD7870F42 ; // ISO polynomial // $poly64rev = (0xD8 << 56); for ( $i = 0 ; $i < 256 ; $i ++) { for ( $part = $i , $bit = 0 ; $bit < 8 ; $bit ++) { if ( $part & 1 ) { $part = (( $part >> 1 ) & ~( 0x8 << 60 )) ^ $poly64rev ; } else { $part = ( $part >> 1 ) & ~( 0x8 << 60 ); } } $crc64tab [ $i ] = $part ; } return $crc64tab ; } /** * @param string $string * @param string $format * @return mixed * * Formats: * crc64('php'); // afe4e823e7cef190 * crc64('php', '0x%x'); // 0xafe4e823e7cef190 * crc64('php', '0x%X'); // 0xAFE4E823E7CEF190 * crc64('php', '%d'); // -5772233581471534704 signed int * crc64('php', '%u'); // 12674510492238016912 unsigned int */ function crc64 ( $string , $format = '%x' ) { static $crc64tab ; if ( $crc64tab === null ) { $crc64tab = crc64Table (); } $crc = 0 ; for ( $i = 0 ; $i < strlen ( $string ); $i ++) { $crc = $crc64tab [( $crc ^ ord ( $string [ $i ])) & 0xff ] ^ (( $crc >> 8 ) & ~( 0xff << 56 )); } return sprintf ( $format , $crc ); } up down 10 JS at JavsSys dot Org ¶ 12 years ago The khash() function by sukitsupaluk has two problems, it does not use all 62 characters from the $map set and when corrected it then produces different results on 64-bit compared to 32-bit PHP systems. Here is my modified version : <?php /** * Small sample convert crc32 to character map * Based upon http://www.php.net/manual/en/function.crc32.php#105703 * (Modified to now use all characters from $map) * (Modified to be 32-bit PHP safe) */ function khash ( $data ) { static $map = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ; $hash = bcadd ( sprintf ( '%u' , crc32 ( $data )) , 0x100000000 ); $str = "" ; do { $str = $map [ bcmod ( $hash , 62 ) ] . $str ; $hash = bcdiv ( $hash , 62 ); } while ( $hash >= 1 ); return $str ; } //----------------------------------------------------------------------------------- $test = array( null , true , false , 0 , "0" , 1 , "1" , "2" , "3" , "ab" , "abc" , "abcd" , "abcde" , "abcdefoo" , "248840027" , "1365848013" , // time() "9223372035488927794" , // PHP_INT_MAX-time() "901131979" , // mt_rand() "Sat, 13 Apr 2013 10:13:33 +0000" // gmdate('r') ); $out = array(); foreach ( $test as $s ) { $out [] = khash ( $s ) . ": " . $s ; } print "<h3>khash() -- maps a crc32 result into a (62-character) result</h3>" ; print '<pre>' ; var_dump ( $out ); print "\n\n\$GLOBALS['raw_crc32']:\n" ; var_dump ( $GLOBALS [ 'raw_crc32' ]); print '</pre><hr>' ; flush (); $pefile = __FILE__ ; print "<h3> $pefile </h3>" ; ob_end_flush (); flush (); highlight_file ( $pefile ); print "<hr>" ; //----------------------------------------------------------------------------------- /* CURRENT output array(19) { [0]=> string(8) "4GFfc4: " [1]=> string(9) "76nO4L: 1" [2]=> string(8) "4GFfc4: " [3]=> string(9) "9aGcIp: 0" [4]=> string(9) "9aGcIp: 0" [5]=> string(9) "76nO4L: 1" [6]=> string(9) "76nO4L: 1" [7]=> string(9) "5b8iNn: 2" [8]=> string(9) "6HmfFN: 3" [9]=> string(10) "7ADPD7: ab" [10]=> string(11) "5F0aUq: abc" [11]=> string(12) "92kWw9: abcd" [12]=> string(13) "78hcpf: abcde" [13]=> string(16) "9eBVPB: abcdefoo" [14]=> string(17) "5TjOuZ: 248840027" [15]=> string(18) "5eNliI: 1365848013" [16]=> string(27) "4Q00e5: 9223372035488927794" [17]=> string(17) "6DUX8V: 901131979" [18]=> string(39) "5i2aOW: Sat, 13 Apr 2013 10:13:33 +0000" } */ //----------------------------------------------------------------------------------- ?> up down 10 Bulk at bulksplace dot com ¶ 20 years ago A faster way I've found to return CRC values of larger files, is instead of using the file()/implode() method used below, is to us file_get_contents() (PHP 4 >= 4.3.0) which uses memory mapping techniques if supported by your OS to enhance performance. Here's my example function: <?php // $file is the path to the file you want to check. function file_crc ( $file ) { $file_string = file_get_contents ( $file ); $crc = crc32 ( $file_string ); return sprintf ( "%u" , $crc ); } $file_to_crc = / home / path / to / file . jpg ; echo file_crc ( $file_to_crc ); // Outputs CRC value for given file. ?> I've found in testing this method is MUCH faster for larger binary files. up down 8 slimshady451 ¶ 18 years ago I see a lot of function for crc32_file, but for php version >= 5.1.2 don't forget you can use this : <?php function crc32_file ( $filename ) { return hash_file ( 'CRC32' , $filename , FALSE ); } ?> Using crc32(file_get_contents($filename)) will use too many memory on big file so don't use it. up down 6 same ¶ 21 years ago bit by bit crc32 computation <?php function bitbybit_crc32 ( $str , $first_call = false ){ //reflection in 32 bits of crc32 polynomial 0x04C11DB7 $poly_reflected = 0xEDB88320 ; //=0xFFFFFFFF; //keep track of register value after each call static $reg = 0xFFFFFFFF ; //initialize register on first call if( $first_call ) $reg = 0xFFFFFFFF ; $n = strlen ( $str ); $zeros = $n < 4 ? $n : 4 ; //xor first $zeros=min(4,strlen($str)) bytes into the register for( $i = 0 ; $i < $zeros ; $i ++) $reg ^= ord ( $str { $i })<< $i * 8 ; //now for the rest of the string for( $i = 4 ; $i < $n ; $i ++){ $next_char = ord ( $str { $i }); for( $j = 0 ; $j < 8 ; $j ++) $reg =(( $reg >> 1 & 0x7FFFFFFF )|( $next_char >> $j & 1 )<< 0x1F ) ^( $reg & 1 )* $poly_reflected ; } //put in enough zeros at the end for( $i = 0 ; $i < $zeros * 8 ; $i ++) $reg =( $reg >> 1 & 0x7FFFFFFF )^( $reg & 1 )* $poly_reflected ; //xor the register with 0xFFFFFFFF return ~ $reg ; } $str = "123456789" ; //whatever $blocksize = 4 ; //whatever for( $i = 0 ; $i < strlen ( $str ); $i += $blocksize ) $crc = bitbybit_crc32 ( substr ( $str , $i , $blocksize ),! $i ); ?> up down 5 dave at jufer dot info ¶ 18 years ago This function returns the same int value on a 64 bit mc. like the crc32() function on a 32 bit mc. <?php function crcKw ( $num ){ $crc = crc32 ( $num ); if( $crc & 0x80000000 ){ $crc ^= 0xffffffff ; $crc += 1 ; $crc = - $crc ; } return $crc ; } ?> up down 3 Clifford dot ct at gmail dot com ¶ 13 years ago The crc32() function can return a signed integer in certain environments. Assuming that it will always return an unsigned integer is not portable. Depending on your desired behavior, you should probably use sprintf() on the result or the generic hash() instead. Also note that integer arithmetic operators do not have the precision to work correctly with the integer output. up down 3 alban dot lopez+php [ at ] gmail dot com ¶ 14 years ago I made this code to verify Transmition with Vantage Pro2 ( weather station ) based on CRC16-CCITT standard. <?php // CRC16-CCITT validator $crc_table = array( 0x0 , 0x1021 , 0x2042 , 0x3063 , 0x4084 , 0x50a5 , 0x60c6 , 0x70e7 , 0x8108 , 0x9129 , 0xa14a , 0xb16b , 0xc18c , 0xd1ad , 0xe1ce , 0xf1ef , 0x1231 , 0x210 , 0x3273 , 0x2252 , 0x52b5 , 0x4294 , 0x72f7 , 0x62d6 , 0x9339 , 0x8318 , 0xb37b , 0xa35a , 0xd3bd , 0xc39c , 0xf3ff , 0xe3de , 0x2462 , 0x3443 , 0x420 , 0x1401 , 0x64e6 , 0x74c7 , 0x44a4 , 0x5485 , 0xa56a , 0xb54b , 0x8528 , 0x9509 , 0xe5ee , 0xf5cf , 0xc5ac , 0xd58d , 0x3653 , 0x2672 , 0x1611 , 0x630 , 0x76d7 , 0x66f6 , 0x5695 , 0x46b4 , 0xb75b , 0xa77a , 0x9719 , 0x8738 , 0xf7df , 0xe7fe , 0xd79d , 0xc7bc , 0x48c4 , 0x58e5 , 0x6886 , 0x78a7 , 0x840 , 0x1861 , 0x2802 , 0x3823 , 0xc9cc , 0xd9ed , 0xe98e , 0xf9af , 0x8948 , 0x9969 , 0xa90a , 0xb92b , 0x5af5 , 0x4ad4 , 0x7ab7 , 0x6a96 , 0x1a71 , 0xa50 , 0x3a33 , 0x2a12 , 0xdbfd , 0xcbdc , 0xfbbf , 0xeb9e , 0x9b79 , 0x8b58 , 0xbb3b , 0xab1a , 0x6ca6 , 0x7c87 , 0x4ce4 , 0x5cc5 , 0x2c22 , 0x3c03 , 0xc60 , 0x1c41 , 0xedae , 0xfd8f , 0xcdec , 0xddcd , 0xad2a , 0xbd0b , 0x8d68 , 0x9d49 , 0x7e97 , 0x6eb6 , 0x5ed5 , 0x4ef4 , 0x3e13 , 0x2e32 , 0x1e51 , 0xe70 , 0xff9f , 0xefbe , 0xdfdd , 0xcffc , 0xbf1b , 0xaf3a , 0x9f59 , 0x8f78 , 0x9188 , 0x81a9 , 0xb1ca , 0xa1eb , 0xd10c , 0xc12d , 0xf14e , 0xe16f , 0x1080 , 0xa1 , 0x30c2 , 0x20e3 , 0x5004 , 0x4025 , 0x7046 , 0x6067 , 0x83b9 , 0x9398 , 0xa3fb , 0xb3da , 0xc33d , 0xd31c , 0xe37f , 0xf35e , 0x2b1 , 0x1290 , 0x22f3 , 0x32d2 , 0x4235 , 0x5214 , 0x6277 , 0x7256 , 0xb5ea , 0xa5cb , 0x95a8 , 0x8589 , 0xf56e , 0xe54f , 0xd52c , 0xc50d , 0x34e2 , 0x24c3 , 0x14a0 , 0x481 , 0x7466 , 0x6447 , 0x5424 , 0x4405 , 0xa7db , 0xb7fa , 0x8799 , 0x97b8 , 0xe75f , 0xf77e , 0xc71d , 0xd73c , 0x26d3 , 0x36f2 , 0x691 , 0x16b0 , 0x6657 , 0x7676 , 0x4615 , 0x5634 , 0xd94c , 0xc96d , 0xf90e , 0xe92f , 0x99c8 , 0x89e9 , 0xb98a , 0xa9ab , 0x5844 , 0x4865 , 0x7806 , 0x6827 , 0x18c0 , 0x8e1 , 0x3882 , 0x28a3 , 0xcb7d , 0xdb5c , 0xeb3f , 0xfb1e , 0x8bf9 , 0x9bd8 , 0xabbb , 0xbb9a , 0x4a75 , 0x5a54 , 0x6a37 , 0x7a16 , 0xaf1 , 0x1ad0 , 0x2ab3 , 0x3a92 , 0xfd2e , 0xed0f , 0xdd6c , 0xcd4d , 0xbdaa , 0xad8b , 0x9de8 , 0x8dc9 , 0x7c26 , 0x6c07 , 0x5c64 , 0x4c45 , 0x3ca2 , 0x2c83 , 0x1ce0 , 0xcc1 , 0xef1f , 0xff3e , 0xcf5d , 0xdf7c , 0xaf9b , 0xbfba , 0x8fd9 , 0x9ff8 , 0x6e17 , 0x7e36 , 0x4e55 , 0x5e74 , 0x2e93 , 0x3eb2 , 0xed1 , 0x1ef0 ); $test = chr ( 0xC6 ). chr ( 0xCE ). chr ( 0xA2 ). chr ( 0x03 ); // CRC16-CCITT = 0xE2B4 genCRC ( $test ); function genCRC (& $ptr ) { $crc = 0x0000 ; $crc_table = $GLOBALS [ 'crc_table' ]; for ( $i = 0 ; $i < strlen ( $ptr ); $i ++) $crc = $crc_table [(( $crc >> 8 ) ^ ord ( $ptr [ $i ]))] ^ (( $crc << 8 ) & 0x00FFFF ); return $crc ; } ?> up down 4 roberto at spadim dot com dot br ¶ 19 years ago MODBUS RTU, CRC16, input-> modbus rtu string output -> 2bytes string, in correct modbus order <?php function crc16 ( $string , $length = 0 ){ $auchCRCHi =array( 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x01 , 0xC0 , 0x80 , 0x41 , 0x00 , 0xC1 , 0x81 , 0x40 ); $auchCRCLo =array( 0x00 , 0xC0 , 0xC1 , 0x01 , 0xC3 , 0x03 , 0x02 , 0xC2 , 0xC6 , 0x06 , 0x07 , 0xC7 , 0x05 , 0xC5 , 0xC4 , 0x04 , 0xCC , 0x0C , 0x0D , 0xCD , 0x0F , 0xCF , 0xCE , 0x0E , 0x0A , 0xCA , 0xCB , 0x0B , 0xC9 , 0x09 , 0x08 , 0xC8 , 0xD8 , 0x18 , 0x19 , 0xD9 , 0x1B , 0xDB , 0xDA , 0x1A , 0x1E , 0xDE , 0xDF , 0x1F , 0xDD , 0x1D , 0x1C , 0xDC , 0x14 , 0xD4 , 0xD5 , 0x15 , 0xD7 , 0x17 , 0x16 , 0xD6 , 0xD2 , 0x12 , 0x13 , 0xD3 , 0x11 , 0xD1 , 0xD0 , 0x10 , 0xF0 , 0x30 , 0x31 , 0xF1 , 0x33 , 0xF3 , 0xF2 , 0x32 , 0x36 , 0xF6 , 0xF7 , 0x37 , 0xF5 , 0x35 , 0x34 , 0xF4 , 0x3C , 0xFC , 0xFD , 0x3D , 0xFF , 0x3F , 0x3E , 0xFE , 0xFA , 0x3A , 0x3B , 0xFB , 0x39 , 0xF9 , 0xF8 , 0x38 , 0x28 , 0xE8 , 0xE9 , 0x29 , 0xEB , 0x2B , 0x2A , 0xEA , 0xEE , 0x2E , 0x2F , 0xEF , 0x2D , 0xED , 0xEC , 0x2C , 0xE4 , 0x24 , 0x25 , 0xE5 , 0x27 , 0xE7 , 0xE6 , 0x26 , 0x22 , 0xE2 , 0xE3 , 0x23 , 0xE1 , 0x21 , 0x20 , 0xE0 , 0xA0 , 0x60 , 0x61 , 0xA1 , 0x63 , 0xA3 , 0xA2 , 0x62 , 0x66 , 0xA6 , 0xA7 , 0x67 , 0xA5 , 0x65 , 0x64 , 0xA4 , 0x6C , 0xAC , 0xAD , 0x6D , 0xAF , 0x6F , 0x6E , 0xAE , 0xAA , 0x6A , 0x6B , 0xAB , 0x69 , 0xA9 , 0xA8 , 0x68 , 0x78 , 0xB8 , 0xB9 , 0x79 , 0xBB , 0x7B , 0x7A , 0xBA , 0xBE , 0x7E , 0x7F , 0xBF , 0x7D , 0xBD , 0xBC , 0x7C , 0xB4 , 0x74 , 0x75 , 0xB5 , 0x77 , 0xB7 , 0xB6 , 0x76 , 0x72 , 0xB2 , 0xB3 , 0x73 , 0xB1 , 0x71 , 0x70 , 0xB0 , 0x50 , 0x90 , 0x91 , 0x51 , 0x93 , 0x53 , 0x52 , 0x92 , 0x96 , 0x56 , 0x57 , 0x97 , 0x55 , 0x95 , 0x94 , 0x54 , 0x9C , 0x5C , 0x5D , 0x9D , 0x5F , 0x9F , 0x9E , 0x5E , 0x5A , 0x9A , 0x9B , 0x5B , 0x99 , 0x59 , 0x58 , 0x98 , 0x88 , 0x48 , 0x49 , 0x89 , 0x4B , 0x8B , 0x8A , 0x4A , 0x4E , 0x8E , 0x8F , 0x4F , 0x8D , 0x4D , 0x4C , 0x8C , 0x44 , 0x84 , 0x85 , 0x45 , 0x87 , 0x47 , 0x46 , 0x86 , 0x82 , 0x42 , 0x43 , 0x83 , 0x41 , 0x81 , 0x80 , 0x40 ); $length =( $length <= 0 ? strlen ( $string ): $length ); $uchCRCHi = 0xFF ; $uchCRCLo = 0xFF ; $uIndex = 0 ; for ( $i = 0 ; $i < $length ; $i ++){ $uIndex = $uchCRCLo ^ ord ( substr ( $string , $i , 1 )); $uchCRCLo = $uchCRCHi ^ $auchCRCHi [ $uIndex ]; $uchCRCHi = $auchCRCLo [ $uIndex ] ; } return( chr ( $uchCRCLo ). chr ( $uchCRCHi )); } ?> up down 2 arachnid at notdot dot net ¶ 21 years ago Note that the CRC32 algorithm should NOT be used for cryptographic purposes, or in situations where a hostile/untrusted user is involved, as it is far too easy to generate a hash collision for CRC32 (two different binary strings that have the same CRC32 hash). Instead consider SHA-1 or MD5. up down 2 sukitsupaluk at hotmail dot com ¶ 14 years ago small sample convert crc32 to character map <?php function khash ( $data ) { static $map = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ; $hash = crc32 ( $data )+ 0x100000000 ; $str = "" ; do { $str = $map [ 31 + ( $hash % 31 )] . $str ; $hash /= 31 ; } while( $hash >= 1 ); return $str ; } $test = array( null , TRUE , FALSE , 0 , "0" , 1 , "1" , "2" , "3" , "ab" , "abc" , "abcd" , "abcde" , "abcdefoo" ); $out = array(); foreach( $test as $s ) { $out []= khash ( $s ). ": " . $s ; } var_dump ( $out ); /* output: array 0 => string 'zVvOYTv: ' (length=9) 1 => string 'xKDKKL8: 1' (length=10) 2 => string 'zVvOYTv: ' (length=9) 3 => string 'zOKCQxh: 0' (length=10) 4 => string 'zOKCQxh: 0' (length=10) 5 => string 'xKDKKL8: 1' (length=10) 6 => string 'xKDKKL8: 1' (length=10) 7 => string 'AFSzIAO: 2' (length=10) 8 => string 'BXGSvQJ: 3' (length=10) 9 => string 'xZWOQSu: ab' (length=11) 10 => string 'AVAwHOR: abc' (length=12) 11 => string 'zKASNE1: abcd' (length=13) 12 => string 'xLCTOV7: abcde' (length=14) 13 => string 'zQLzKMt: abcdefoo' (length=17) */ ?> up down 1 chernyshevsky at hotmail dot com ¶ 15 years ago The crc32_combine() function provided by petteri at qred dot fi has a bug that causes an infinite loop, a shift operation on a 32-bit signed int might never reach zero. Replacing the function gf2_matrix_times() with the following seems to fix it: <?php function gf2_matrix_times ( $mat , $vec ) { $sum = 0 ; $i = 0 ; while ( $vec ) { if ( $vec & 1 ) { $sum ^= $mat [ $i ]; } $vec = ( $vec >> 1 ) & 0x7FFFFFFF ; $i ++; } return $sum ; } ?> Otherwise, it's probably the best solution if you can't use hash_file(). Using a 1meg read buffer, the function only takes twice as long to process a 300meg files than hash_file() in my test. up down 1 berna (at) gensis (dot) com (dot) br ¶ 16 years ago For those who want a more familiar return value for the function: <?php function strcrc32 ( $text ) { $crc = crc32 ( $text ); if ( $crc & 0x80000000 ) { $crc ^= 0xffffffff ; $crc += 1 ; $crc = - $crc ; } return $crc ; } ?> And to show the result in Hex string: <?php function int32_to_hex ( $value ) { $value &= 0xffffffff ; return str_pad ( strtoupper ( dechex ( $value )), 8 , "0" , STR_PAD_LEFT ); } ?> up down 1 arris at zsolttech dot com ¶ 14 years ago not found anywhere crc64 based on http://bioinfadmin.cs.ucl.ac.uk/downloads/crc64/crc64.c . (use gmp module) <?php /* OLDCRC */ define ( 'POLY64REV' , "d800000000000000" ); define ( 'INITIALCRC' , "0000000000000000" ); define ( 'TABLELEN' , 256 ); /* NEWCRC */ // define('POLY64REV', "95AC9329AC4BC9B5"); // define('INITIALCRC', "FFFFFFFFFFFFFFFF"); if( function_exists ( 'gmp_init' )){ class CRC64 { private static $CRCTable = array(); public static function encode ( $seq ){ $crc = gmp_init ( INITIALCRC , 16 ); $init = FALSE ; $poly64rev = gmp_init ( POLY64REV , 16 ); if (! $init ) { $init = TRUE ; for ( $i = 0 ; $i < TABLELEN ; $i ++) { $part = gmp_init ( $i , 10 ); for ( $j = 0 ; $j < 8 ; $j ++) { if ( gmp_strval ( gmp_and ( $part , "0x1" )) != "0" ){ // if (gmp_testbit($part, 1)){ /* PHP 5 >= 5.3.0, untested */ $part = gmp_xor ( gmp_div_q ( $part , "2" ), $poly64rev ); } else { $part = gmp_div_q ( $part , "2" ); } } self :: $CRCTable [ $i ] = $part ; } } for( $k = 0 ; $k < strlen ( $seq ); $k ++){ $tmp_gmp_val = gmp_init ( ord ( $seq [ $k ]), 10 ); $tableindex = gmp_xor ( gmp_and ( $crc , "0xff" ), $tmp_gmp_val ); $crc = gmp_div_q ( $crc , "256" ); $crc = gmp_xor ( $crc , self :: $CRCTable [ gmp_strval ( $tableindex , 10 )]); } $res = gmp_strval ( $crc , 16 ); return $res ; } } } else { die( "Please install php-gmp package!!!" ); } ?> up down 1 quix at free dot fr ¶ 22 years ago I needed the crc32 of a file that was pretty large, so I didn't want to read it into memory. So I made this: <?php $GLOBALS [ '__crc32_table' ]=array(); // Lookup table array __crc32_init_table (); function __crc32_init_table () { // Builds lookup table array // This is the official polynomial used by // CRC-32 in PKZip, WinZip and Ethernet. $polynomial = 0x04c11db7 ; // 256 values representing ASCII character codes. for( $i = 0 ; $i <= 0xFF ;++ $i ) { $GLOBALS [ '__crc32_table' ][ $i ]=( __crc32_reflect ( $i , 8 ) << 24 ); for( $j = 0 ; $j < 8 ;++ $j ) { $GLOBALS [ '__crc32_table' ][ $i ]=(( $GLOBALS [ '__crc32_table' ][ $i ] << 1 ) ^ (( $GLOBALS [ '__crc32_table' ][ $i ] & ( 1 << 31 ))? $polynomial : 0 )); } $GLOBALS [ '__crc32_table' ][ $i ] = __crc32_reflect ( $GLOBALS [ '__crc32_table' ][ $i ], 32 ); } } function __crc32_reflect ( $ref , $ch ) { // Reflects CRC bits in the lookup table $value = 0 ; // Swap bit 0 for bit 7, bit 1 for bit 6, etc. for( $i = 1 ; $i <( $ch + 1 );++ $i ) { if( $ref & 1 ) $value |= ( 1 << ( $ch - $i )); $ref = (( $ref >> 1 ) & 0x7fffffff ); } return $value ; } function __crc32_string ( $text ) { // Creates a CRC from a text string // Once the lookup table has been filled in by the two functions above, // this function creates all CRCs using only the lookup table. // You need unsigned variables because negative values // introduce high bits where zero bits are required. // PHP doesn't have unsigned integers: // I've solved this problem by doing a '&' after a '>>'. // Start out with all bits set high. $crc = 0xffffffff ; $len = strlen ( $text ); // Perform the algorithm on each character in the string, // using the lookup table values. for( $i = 0 ; $i < $len ;++ $i ) { $crc =(( $crc >> 8 ) & 0x00ffffff ) ^ $GLOBALS [ '__crc32_table' ][( $crc & 0xFF ) ^ ord ( $text { $i })]; } // Exclusive OR the result with the beginning value. return $crc ^ 0xffffffff ; } function __crc32_file ( $name ) { // Creates a CRC from a file // Info: look at __crc32_string // Start out with all bits set high. $crc = 0xffffffff ; if(( $fp = fopen ( $name , 'rb' ))=== false ) return false ; // Perform the algorithm on each character in file for(;;) { $i =@ fread ( $fp , 1 ); if( strlen ( $i )== 0 ) break; $crc =(( $crc >> 8 ) & 0x00ffffff ) ^ $GLOBALS [ '__crc32_table' ][( $crc & 0xFF ) ^ ord ( $i )]; } @ fclose ( $fp ); // Exclusive OR the result with the beginning value. return $crc ^ 0xffffffff ; } ?> up down 1 spectrumizer at cycos dot net ¶ 23 years ago Here is a tested and working CRC16-Algorithm: <?php function crc16 ( $string ) { $crc = 0xFFFF ; for ( $x = 0 ; $x < strlen ( $string ); $x ++) { $crc = $crc ^ ord ( $string [ $x ]); for ( $y = 0 ; $y < 8 ; $y ++) { if (( $crc & 0x0001 ) == 0x0001 ) { $crc = (( $crc >> 1 ) ^ 0xA001 ); } else { $crc = $crc >> 1 ; } } } return $crc ; } ?> Regards, Mario up down 1 Ren ¶ 18 years ago Dealing with 32 bit unsigned values overflowing 32 bit php signed values can be done by adding 0x10000000 to any unexpected negative result, rather than using sprintf. $i = crc32('1'); printf("%u\n", $i); if (0 > $i) { // Implicitly casts i as float, and corrects this sign. $i += 0x100000000; } var_dump($i); Outputs: 2212294583 float(2212294583) up down 0 dotg at mail dot ru ¶ 9 years ago crc32() on php 32bit and 64 bit not equal in some values i use abs for result in positive for 32 bit not equal <?=abs ( crc32 ( 1 )); ?> 64 bit 2212294583 32 bit 2082672713 equal <?=abs ( crc32 ( 3 )); ?> 64 bit 1842515611 32 bit 1842515611 up down 0 toggio at writeme dot com ¶ 9 years ago A faster implementation of modbus CRC16 function crc16($data) { $crc = 0xFFFF; for ($i = 0; $i < strlen($data); $i++) { $crc ^=ord($data[$i]); for ($j = 8; $j !=0; $j--) { if (($crc & 0x0001) !=0) { $crc >>= 1; $crc ^= 0xA001; } else $crc >>= 1; } } return $crc; } up down -1 mail at tristansmis dot nl ¶ 18 years ago I used the abs value of this function on a 32-bit system. When porting the code to a 64-bit system I’ve found that the value is different. The following code has the same outcome on both systems. <?php $crc = abs ( crc32 ( $string )); if( $crc & 0x80000000 ){ $crc ^= 0xffffffff ; $crc += 1 ; } /* Old solution * $crc = abs(crc32($string)) */ ?> up down -2 gabri dot ns at gmail dot com ¶ 15 years ago if you are looking for a fast function to hash a file, take a look at http://www.php.net/manual/en/function.hash-file.php this is crc32 file checker based on a CRC32 guide it have performance at ~ 625 KB/s on my 2.2GHz Turion far slower than hash_file('crc32b','filename.ext') <?php function crc32_file ( $filename ) { $f = @ fopen ( $filename , 'rb' ); if (! $f ) return false ; static $CRC32Table , $Reflect8Table ; if (!isset( $CRC32Table )) { $Polynomial = 0x04c11db7 ; $topBit = 1 << 31 ; for( $i = 0 ; $i < 256 ; $i ++) { $remainder = $i << 24 ; for ( $j = 0 ; $j < 8 ; $j ++) { if ( $remainder & $topBit ) $remainder = ( $remainder << 1 ) ^ $Polynomial ; else $remainder = $remainder << 1 ; } $CRC32Table [ $i ] = $remainder ; if (isset( $Reflect8Table [ $i ])) continue; $str = str_pad ( decbin ( $i ), 8 , '0' , STR_PAD_LEFT ); $num = bindec ( strrev ( $str )); $Reflect8Table [ $i ] = $num ; $Reflect8Table [ $num ] = $i ; } } $remainder = 0xffffffff ; while ( $data = fread ( $f , 1024 )) { $len = strlen ( $data ); for ( $i = 0 ; $i < $len ; $i ++) { $byte = $Reflect8Table [ ord ( $data [ $i ])]; $index = (( $remainder >> 24 ) & 0xff ) ^ $byte ; $crc = $CRC32Table [ $index ]; $remainder = ( $remainder << 8 ) ^ $crc ; } } $str = decbin ( $remainder ); $str = str_pad ( $str , 32 , '0' , STR_PAD_LEFT ); $remainder = bindec ( strrev ( $str )); return $remainder ^ 0xffffffff ; } ?> <?php $a = microtime (); echo dechex ( crc32_file ( 'filename.ext' )). "\n" ; $b = microtime (); echo array_sum ( explode ( ' ' , $b )) - array_sum ( explode ( ' ' , $a )). "\n" ; ?> Output: ec7369fe 2.384134054184 (or similiar) + add a note String Функції addcslashes addslashes bin2hex chop chr chunk_​split convert_​uudecode convert_​uuencode count_​chars crc32 crypt echo explode fprintf get_​html_​translation_​table hebrev hex2bin html_​entity_​decode htmlentities htmlspecialchars htmlspecialchars_​decode implode join lcfirst levenshtein localeconv ltrim md5 md5_​file metaphone nl_​langinfo nl2br number_​format ord parse_​str print printf quoted_​printable_​decode quoted_​printable_​encode quotemeta rtrim setlocale sha1 sha1_​file similar_​text soundex sprintf sscanf str_​contains str_​decrement str_​ends_​with str_​getcsv str_​increment str_​ireplace str_​pad str_​repeat str_​replace str_​rot13 str_​shuffle str_​split str_​starts_​with str_​word_​count strcasecmp strchr strcmp strcoll strcspn strip_​tags stripcslashes stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk strpos strrchr strrev strripos strrpos strspn strstr strtok strtolower strtoupper strtr substr substr_​compare substr_​count substr_​replace trim ucfirst ucwords vfprintf vprintf vsprintf wordwrap Deprecated convert_​cyr_​string hebrevc money_​format utf8_​decode utf8_​encode Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
http://www.php.net/mcrypt_create_iv | PHP: mcrypt_create_iv - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box mcrypt_decrypt » « Mcrypt Functions PHP Manual Function Reference Cryptography Extensions Mcrypt Mcrypt Functions Change language: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other mcrypt_create_iv (PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) mcrypt_create_iv — Creates an initialization vector (IV) from a random source Warning This function was DEPRECATED in PHP 7.1.0, and REMOVED in PHP 7.2.0. Alternatives to this function include: random_bytes() Description mcrypt_create_iv ( int $size , int $source = MCRYPT_DEV_URANDOM ): string Creates an initialization vector (IV) from a random source. The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without losing security. Parameters size The size of the IV. source The source of the IV. The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random ) and MCRYPT_DEV_URANDOM (read data from /dev/urandom ). Prior to 5.3.0, MCRYPT_RAND was the only one supported on Windows. Note that the default value of this parameter was MCRYPT_DEV_RANDOM prior to PHP 5.6.0. Note : Note that MCRYPT_DEV_RANDOM may block until more entropy is available. Return Values Returns the initialization vector, or false on error. Examples Example #1 mcrypt_create_iv() Example <?php $size = mcrypt_get_iv_size ( MCRYPT_CAST_256 , MCRYPT_MODE_CFB ); $iv = mcrypt_create_iv ( $size , MCRYPT_DEV_RANDOM ); ?> See Also » http://www.ciphersbyritter.com/GLOSSARY.HTM#IV » http://www.quadibloc.com/crypto/co0409.htm Chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) random_bytes() - Get cryptographically secure random bytes Found A Problem? Learn How To Improve This Page • Submit a Pull Request • Report a Bug + add a note User Contributed Notes 2 notes up down 44 Graham ¶ 11 years ago In relation to all of the crypto "advice" seen here, my suggestion is that you ignore most of it. Some of it is good, some of it is bad, but most of it skips the critical issues. I had hoped to write out a nice long explanation, but PHP's commenting system tells me my essay is too long. Instead I will say this: You should use CBC, with a randomly chosen IV that is unique per key, and you should transmit that IV in the clear along with your ciphertext. You should also perform an authenticity check of that entire data blob, using something like HMAC-SHA256, with another independent key. Here's the full-text of what I was going to write: http://pastebin.com/sN6buivY If you're interested in this stuff, or just want more information, check out the Wikipedia articles around block cipher modes, block ciphers, HMAC, etc. I also suggest reading Practical Cryptography by Bruce Schneier, as well as Cryptography Engineering by Niels Ferguson, both of which are very easy-to-digest books on practical cryptography. up down 17 Chris ¶ 19 years ago >First, the IV should be random and variable. The whole >point of it is to ensure that the same plaintext does not >encrypt to the same ciphertext every time. You most >certainly do lose security if the IV is constant or public. Wrong, Wrong WRONG! The initialization vector is ALLOWED to be PUBLIC! It is generally sent along with the ciphertext, UNENCRYPTED. >The ciphertext should be E(IV | plaintext, key) Wrong again! The initialization vector is NOT prepended to the plaintext before encryption. The IV is used to seed the feedback system! (which is why you don't need one in ECB mode - there is no feedback) >Second, the IV should not be part of the decryption >parameters at all. You should be able to decrypt the cipher >text, throw away the initial vector at the front w/o even >reading it, and have your plaintext: Nope. You need to seed the feedback mechanism during decryption to the SAME state as it was seeded during encryption. This means using the SAME IV! + add a note Mcrypt Functions mcrypt_​create_​iv mcrypt_​decrypt mcrypt_​enc_​get_​algorithms_​name mcrypt_​enc_​get_​block_​size mcrypt_​enc_​get_​iv_​size mcrypt_​enc_​get_​key_​size mcrypt_​enc_​get_​modes_​name mcrypt_​enc_​get_​supported_​key_​sizes mcrypt_​enc_​is_​block_​algorithm mcrypt_​enc_​is_​block_​algorithm_​mode mcrypt_​enc_​is_​block_​mode mcrypt_​enc_​self_​test mcrypt_​encrypt mcrypt_​generic mcrypt_​generic_​deinit mcrypt_​generic_​init mcrypt_​get_​block_​size mcrypt_​get_​cipher_​name mcrypt_​get_​iv_​size mcrypt_​get_​key_​size mcrypt_​list_​algorithms mcrypt_​list_​modes mcrypt_​module_​close mcrypt_​module_​get_​algo_​block_​size mcrypt_​module_​get_​algo_​key_​size mcrypt_​module_​get_​supported_​key_​sizes mcrypt_​module_​is_​block_​algorithm mcrypt_​module_​is_​block_​algorithm_​mode mcrypt_​module_​is_​block_​mode mcrypt_​module_​open mcrypt_​module_​self_​test mdecrypt_​generic Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://www.timeforkids.com/contact-us/ | TIME for Kids | Contact Us Skip to main content Get a Quote Subscribe Articles by Grade level Grades K-1 Articles Grade 2 Articles Grades 3-4 Articles Grades 5-6 Articles Topics Animals Arts Ask Angela Books Business Careers Community Culture Debate Earth Science Education Election 2024 Engineering Environment Food and Nutrition Games Government History Holidays Inventions Movies and Television Music and Theater Nature News People Places Podcasts Science Service Stars Space Sports The Human Body The View Transportation Weather World Young Game Changers Your $ Financial Literacy Content Grade 4 Edition Grade 5-6 Edition For Grown-ups Resource Spotlight Also from TIME for Kids: Log In role: none user_age: none editions: The page you are about to enter is for grown-ups. Enter your birth date to continue. Month (MM) 01 02 03 04 05 06 07 08 09 10 11 12 Year (YYYY) 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 Submit SUBSCRIBE NOW AND SAVE TODAY! Contact Us Customer Service For assistance subscribing or to connect with a customer service representative, email us at tfkcustserv@cdsfulfillment.com . To contact us via phone, please call us at 1-800-777-8600 for U.S. and Canada subscriptions OR 515-283-0979 for all other countries. Editorial To send questions and comments to the editors of TIME for Kids, please email at tfkeditors@time.com . Editorial Address: TIME for Kids 3 Bryant Park, 6th Floor New York, NY 10036 Billing For questions about your bill, please email tfkcustserv@cdsfulfillment.com . To contact us via phone, please call us at 1-800-777-8600 for U.S. and Canada subscriptions OR 515-283-0979 for all other countries. Billing Address: TIME for Kids P.O. Box 37508 Boone, IA 50037-0508 Education To ask a question about curriculum, email the editors of TIME for Kids at tfkteachers@time.com . Grown-Ups Continue Navigate the news, together. Discover TIME for Kids for educators and families. Kids Explore Unlock a world of exciting stories. Start reading the news! News for You! Select your grade to begin reading. K-1 2 3-4 5-6 Contact us Privacy policy California privacy Terms of Service Subscribe CLASSROOM INTERNATIONAL © 2026 TIME USA, LLC. All Rights Reserved. Powered by WordPress.com VIP | 2026-01-13T09:30:39 |
https://www.php.net/manual/it/function.tidy-get-output.php | PHP: tidy_get_output - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box tidy_warning_count » « tidy_error_count Manuale PHP Guida Funzioni Altre estensioni fondamentali Tidy Tidy Funzioni Change language: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other tidy_get_output (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) tidy_get_output — Return a string representing the parsed tidy markup Descrizione tidy_get_output ( tidy $tidy ): string Gets a string with the repaired html. Elenco dei parametri tidy L'oggetto Tidy Valori restituiti Returns the parsed tidy markup. Esempi Example #1 tidy_get_output() example <?php $html = '<p>paragraph</i>' ; $tidy = tidy_parse_string ( $html ); $tidy -> cleanRepair (); echo tidy_get_output ( $tidy ); ?> Il precedente esempio visualizzerà: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <title></title> </head> <body> <p>paragraph</p> </body> </html> Found A Problem? Learn How To Improve This Page • Submit a Pull Request • Report a Bug + add a note User Contributed Notes 1 note up down 1 jon+php_net at phpsitesolutions dot com ¶ 17 years ago If you don't feel like going procedural to get the HTML output, you can simple use this alternative: <?php $html = <<<HTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd "> <html xmlns=" http://www.w3.org/1999/xhtml " xml:lang="en" lang="en"> <head><title>title</title></head> <body> <p>paragraph <br /> text</p> </body></html> HTML; $tidy = new tidy ; $tidy -> parseString ( $html ); $tidy -> cleanRepair (); echo $tidy -> html ()-> value ; ?> You can even more simply access the HTML output via this: <?php echo $tidy -> value ; ?> + add a note Tidy Funzioni ob_​tidyhandler tidy_​access_​count tidy_​config_​count tidy_​error_​count tidy_​get_​output tidy_​warning_​count Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/structNestedName.html#pub-methods | LLVM: NestedName Struct Reference LLVM  22.0.0git Public Member Functions | Public Attributes | List of all members NestedName Struct Reference #include " llvm/Demangle/ItaniumDemangle.h " Inheritance diagram for NestedName: This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead. [ legend ] Public Member Functions   NestedName ( Node *Qual_, Node *Name_) template<typename Fn> void  match (Fn F ) const std::string_view  getBaseName () const override void  printLeft ( OutputBuffer &OB) const override Public Member Functions inherited from Node   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Public Attributes Node *  Qual Node *  Name Additional Inherited Members Public Types inherited from Node enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Protected Attributes inherited from Node Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Detailed Description Definition at line 1077 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  NestedName() NestedName::NestedName ( Node * Qual_ , Node * Name_  ) inline Definition at line 1081 of file ItaniumDemangle.h . References Name , Node::Node() , and Qual . Member Function Documentation ◆  getBaseName() std::string_view NestedName::getBaseName ( ) const inline override virtual Reimplemented from Node . Definition at line 1086 of file ItaniumDemangle.h . References Name . ◆  match() template<typename Fn> void NestedName::match ( Fn F ) const inline Definition at line 1084 of file ItaniumDemangle.h . References F , Name , and Qual . ◆  printLeft() void NestedName::printLeft ( OutputBuffer & OB ) const inline override virtual Implements Node . Definition at line 1088 of file ItaniumDemangle.h . References Name , Node::OutputBuffer , and Qual . Member Data Documentation ◆  Name Node * NestedName::Name Definition at line 1079 of file ItaniumDemangle.h . Referenced by getBaseName() , match() , NestedName() , and printLeft() . ◆  Qual Node * NestedName::Qual Definition at line 1078 of file ItaniumDemangle.h . Referenced by match() , NestedName() , and printLeft() . The documentation for this struct was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Objects | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://www.php.net/manual/ja/function.tidy-warning-count.php | PHP: tidy_warning_count - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box Tokenizer » « tidy_get_output PHP マニュアル 関数リファレンス その他の基本モジュール Tidy Tidy 関数 Change language: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other tidy_warning_count (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) tidy_warning_count — 指定したドキュメントについて発生した Tidy 警告の数を返す 説明 tidy_warning_count ( tidy $tidy ): int 指定したドキュメントについて発生した Tidy 警告の数を返します。 パラメータ tidy Tidy オブジェクト。 戻り値 警告の数を返します。 例 例1 tidy_warning_count() の例 <?php $html = '<p>test</i> <bogustag>bogus</bogustag>' ; $tidy = tidy_parse_string ( $html ); echo tidy_error_count ( $tidy ) . "\n" ; //1 echo tidy_warning_count ( $tidy ) . "\n" ; //5 ?> 参考 tidy_error_count() - 指定したドキュメントについて発生した Tidy エラーの数を返す tidy_access_count() - 指定したドキュメントについて発生したTidyアクセシビリティ警告の数を返す Found A Problem? Learn How To Improve This Page • Submit a Pull Request • Report a Bug + add a note User Contributed Notes There are no user contributed notes for this page. Tidy 関数 ob_​tidyhandler tidy_​access_​count tidy_​config_​count tidy_​error_​count tidy_​get_​output tidy_​warning_​count Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://lists.llvm.org/pipermail/llvm-dev/2006-December/date.html#7550 | The llvm-dev December 2006 Archive by date December 2006 Archives by date Messages sorted by: [ thread ] [ subject ] [ author ] More info on this list... Starting: Fri Dec 1 02:41:28 PST 2006 Ending: Sun Dec 31 13:37:09 PST 2006 Messages: 245 [LLVMdev] Changing pointer representation? Jules [LLVMdev] moving to svn? Chris Morgan [LLVMdev] Changing pointer representation? Vikram S. Adve [LLVMdev] DSGraph::computeCalleeCallerMapping failing Swarup Kumar Sahoo [LLVMdev] DSGraph::computeCalleeCallerMapping failing Andrew Lenharth [LLVMdev] Changing pointer representation? Chris Lattner [LLVMdev] combined arm patch Rafael Espíndola [LLVMdev] DSGraph::computeCalleeCallerMapping failing Swarup Kumar Sahoo [LLVMdev] Disable Inlining Ryan M. Lefever [LLVMdev] crtend Ryan M. Lefever [LLVMdev] Disable Inlining Chris Lattner [LLVMdev] crtend Chris Lattner [LLVMdev] invalid bytecode signature Ryan M. Lefever [LLVMdev] invalid bytecode signature Reid Spencer [LLVMdev] invalid bytecode signature Ryan M. Lefever [LLVMdev] invalid bytecode signature Chris Lattner [LLVMdev] invalid bytecode signature Ralph Corderoy [LLVMdev] combined arm patch Jim Laskey [LLVMdev] weird analysis group behavior Ryan M. Lefever [LLVMdev] problem building gcc4 front end on fedora core 5 Ram Bhamidipaty [LLVMdev] problem building gcc4 front end on fedora core 5 Reid Spencer [LLVMdev] problem building gcc4 front end on fedora core 5 Jim Laskey [LLVMdev] problem building gcc4 front end on fedora core 5 Ram Bhamidipaty [LLVMdev] timer mem stats not implemented? Ryan M. Lefever [LLVMdev] timer mem stats not implemented? Chris Lattner [LLVMdev] # operands < # args Ryan M. Lefever [LLVMdev] problem using scc_iterator on CallGraph Ryan M. Lefever [LLVMdev] LLVM Conference 2007 ? Owen Anderson [LLVMdev] Reminder: LLVM Conference 2007 Poll Reid Spencer [LLVMdev] EH and C++ integration Žiga Osolin [LLVMdev] Dropping support for llvm-gcc3 Reid Spencer [LLVMdev] combined arm patch Rafael Espíndola [LLVMdev] # operands < # args Chris Lattner [LLVMdev] problem using scc_iterator on CallGraph Chris Lattner [LLVMdev] problem using scc_iterator on CallGraph Ryan M. Lefever [LLVMdev] combined arm patch Jim Laskey [LLVMdev] combined arm patch Jim Laskey [LLVMdev] combined arm patch Jim Laskey [LLVMdev] [llvm-commits] combined arm patch Jim Laskey [LLVMdev] [llvm-commits] combined arm patch Rafael Espíndola [LLVMdev] possible bug in X86TargetLowering::getRegClassForInlineAsmConstraint Lauro Ramos Venancio [LLVMdev] [llvm-commits] combined arm patch Jim Laskey [LLVMdev] [patch] getRegClassForInlineAsmConstraint for ARM Lauro Ramos Venancio [LLVMdev] possible bug in X86TargetLowering::getRegClassForInlineAsmConstraint Chris Lattner [LLVMdev] [patch] getRegClassForInlineAsmConstraint for ARM Lauro Ramos Venancio [LLVMdev] Fwd: Compiler opportunities at Cray Vikram S. Adve [LLVMdev] Fwd: Compiler opportunities at Cray Vikram S. Adve [LLVMdev] Fwd: Compiler opportunities at Cray Chris Lattner [LLVMdev] weak linkage Rafael Espíndola [LLVMdev] arm patch 1/n Rafael Espíndola [LLVMdev] arm patch 2/n Rafael Espíndola [LLVMdev] Full C++ support Žiga Osolin [LLVMdev] Full C++ support Reid Spencer [LLVMdev] arm patch 3/n Rafael Espíndola [LLVMdev] [llvm-commits] combined arm patch Rafael Espíndola [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] [llvm-commits] combined arm patch Rafael Espíndola [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] weak linkage Chris Lattner [LLVMdev] weak linkage Rafael Espíndola [LLVMdev] MachineConstantPoolValue Rafael Espíndola [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] MachineConstantPoolValue Anton Korobeynikov [LLVMdev] llc doesn't work in release build Anton Vayvod [LLVMdev] llc doesn't work in release build Reid Spencer [LLVMdev] [patch] print ".weak" directive Rafael Espíndola [LLVMdev] #include <iostream> Bill Wendling [LLVMdev] #include <iostream> Chris Lattner [LLVMdev] Proposed: first class packed structures Chris Lattner [LLVMdev] [patch] print ".weak" directive Chris Lattner [LLVMdev] MachineConstantPoolValue Chris Lattner [LLVMdev] Proposed: first class packed structures Chris Lattner [LLVMdev] Proposed: first class packed structures Reid Spencer [LLVMdev] #include <iostream> Vladimir Prus [LLVMdev] Proposed: first class packed structures Chris Lattner [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] #include <iostream> Bill Wendling [LLVMdev] #include <iostream> Bill Wendling [LLVMdev] MachineConstantPoolValue Rafael Espíndola [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] llvm build not respecting DESTDIR? Reid Spencer [LLVMdev] Proposed: first class packed structures Andrew Lenharth [LLVMdev] llvm build not respecting DESTDIR? Ralph Corderoy [LLVMdev] Bytecode change Andrew Lenharth [LLVMdev] [patch] print ".weak" directive Rafael Espíndola [LLVMdev] #include <iostream> Chris Lattner [LLVMdev] Proposed: first class packed structures Chris Lattner [LLVMdev] Removing DSA from LLVM John Criswell [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] llvm build not respecting DESTDIR? Reid Spencer [LLVMdev] Removing DSA from LLVM Ryan M. Lefever [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] jit with external functions Ram Bhamidipaty [LLVMdev] Removing DSA from LLVM Vikram Sadanand Adve [LLVMdev] Removing DSA from LLVM Chris Lattner [LLVMdev] jit with external functions Chris Lattner [LLVMdev] [PATCH] print .weak directives Rafael Espíndola [LLVMdev] jit with external functions Ram Bhamidipaty [LLVMdev] jit with external functions Chris Lattner [LLVMdev] [PATCH] print .weak directives Chris Lattner [LLVMdev] [PATCH] print .weak directives Rafael Espíndola [LLVMdev] jit with external functions Ram Bhamidipaty [LLVMdev] [patch] emit .weak for zero initialized weak variables Rafael Espíndola [LLVMdev] [patch] move ExtWeakSymbols to AsmPrinter Rafael Espíndola [LLVMdev] llvm build not respecting DESTDIR? Reid Spencer [LLVMdev] Building llvm-gcc4 on amd64 Domagoj Babic [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Domagoj Babic [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Chandler Carruth [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Reid Spencer [LLVMdev] Building llvm-gcc4 on amd64 Chris Lattner [LLVMdev] [patch] move ExtWeakSymbols to AsmPrinter Chris Lattner [LLVMdev] [PATCH] print .weak directives Chris Lattner [LLVMdev] problem using scc_iterator on CallGraph Chris Lattner [LLVMdev] [patch] move ExtWeakSymbols to AsmPrinter Rafael Espíndola [LLVMdev] #include <iostream> John Criswell [LLVMdev] #include <iostream> Bill Wendling [LLVMdev] [patch] llvm-gcc support for packed structures Andrew Lenharth [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Scott Michel [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Domagoj Babic [LLVMdev] [patch] move ExtWeakSymbols to AsmPrinter Rafael Espíndola [LLVMdev] How to compile apps to bc files with the new llvm-gcc4? Scott Michel [LLVMdev] Potential LLVM Service Outages John Criswell [LLVMdev] problems with the legalizer Rafael Espíndola [LLVMdev] [patch] arm bugfix: invalid add/sub constant Lauro Ramos Venancio [LLVMdev] More LLVM Mail Server Downtime John Criswell [LLVMdev] DSA Removed John Criswell [LLVMdev] DSA Removed Chris Lattner [LLVMdev] problems with the legalizer Chris Lattner [LLVMdev] Reminder: LLVM Conference 2007 Reid Spencer [LLVMdev] Instruction sets requiring more than 3 operands Seung Jae Lee [LLVMdev] Instructions having variable names as operands Seung Jae Lee [LLVMdev] MachineFunction.cpp!!! Bill Wendling [LLVMdev] MachineFunction.cpp!!! Jim Laskey [LLVMdev] ThisCall / Compilation problems David Shipman [LLVMdev] ThisCall / Compilation problems Anton Korobeynikov [LLVMdev] ThisCall / Compilation problems Reid Spencer [LLVMdev] ThisCall / Compilation problems Bill Wendling [LLVMdev] Instruction sets requiring more than 3 operands Evan Cheng [LLVMdev] Instructions having variable names as operands Chris Lattner [LLVMdev] ThisCall / Compilation problems Žiga Osolin [LLVMdev] ThisCall / Compilation problems Jeff Cohen [LLVMdev] [patch] move ExtWeakSymbols to AsmPrinter Chris Lattner [LLVMdev] [patch] emit .weak for zero initialized weak variables Chris Lattner [LLVMdev] No crt2.o file found Matthew Bromberg [LLVMdev] No crt2.o file found Anton Korobeynikov [LLVMdev] Building Qt with LLVM Anton Korobeynikov [LLVMdev] Building Qt with LLVM Chris Lattner [LLVMdev] No crt2.o file found Matthew Bromberg [LLVMdev] [patch] emit .weak for zero initialized weak variables Rafael Espíndola [LLVMdev] No crt2.o file found Anton Korobeynikov [LLVMdev] [patch] emit .weak for zero initialized weak variables Chris Lattner [LLVMdev] Books, papers and information Fredrik Svensson [LLVMdev] No crt2.o file found Anton Korobeynikov [LLVMdev] Post-increments and pre-decrements Roman Levenstein [LLVMdev] Books, papers and information Reid Spencer [LLVMdev] Books, papers and information Jeff Cohen [LLVMdev] Books, papers and information Ramana Radhakrishnan [LLVMdev] Post-increments and pre-decrements Evan Cheng [LLVMdev] alias-aware scheduling Dan Gohman [LLVMdev] alias-aware scheduling Evan Cheng [LLVMdev] New PassManager Devang Patel [LLVMdev] Statistic API change Chris Lattner [LLVMdev] alias-aware scheduling Chris Lattner [LLVMdev] post-dominance frontier Ryan M. Lefever [LLVMdev] alias-aware scheduling Dan Gohman [LLVMdev] alias-aware scheduling Evan Cheng [LLVMdev] Problems with new bytecode format Roman Levenstein [LLVMdev] Problems with new bytecode format Bill Wendling [LLVMdev] Books, papers and information Zhongxing Xu [LLVMdev] Problems with new bytecode format Reid Spencer [LLVMdev] Books, papers and information Chris Lattner [LLVMdev] Problems with new bytecode format Roman Levenstein [LLVMdev] Problems with new bytecode format Reid Spencer [LLVMdev] Instruction sets requiring more than 3 operands Seung Jae Lee [LLVMdev] Building llvm-gcc4 on amd64 Chandler Carruth [LLVMdev] Instructions having variable names as operands Seung Jae Lee [LLVMdev] Instructions having variable names as operands Chris Lattner [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] Instructions having variable names as operands Seung Jae Lee [LLVMdev] llvm build not respecting DESTDIR? Erick Tryzelaar [LLVMdev] [patch] arm: external weak in constant pool Lauro Ramos Venancio [LLVMdev] Soft-float Roman Levenstein [LLVMdev] Memory protection using run-time checks Roman Levenstein [LLVMdev] Building llvm-gcc4 on amd64 Domagoj Babic [LLVMdev] Building llvm-gcc4 Reid Spencer [LLVMdev] [patch] arm: external weak in constant pool Bill Wendling [LLVMdev] Instructions having variable names as operands Chris Lattner [LLVMdev] Soft-float Chris Lattner [LLVMdev] Soft-float Evan Cheng [LLVMdev] Soft-float Roman Levenstein [LLVMdev] [patch] arm: external weak in constant pool Lauro Ramos Venancio [LLVMdev] Soft-float Evan Cheng [LLVMdev] Instruction sets requiring more than 3 operands Evan Cheng [LLVMdev] lli, llvm-ld and runtime libraries Erick Tryzelaar [LLVMdev] LLVM capability question. Michael T. Richter [LLVMdev] Instructions having variable names as operands Nikolaos Kavvadias [LLVMdev] LLVM capability question. Ralph Corderoy [LLVMdev] lli, llvm-ld and runtime libraries Reid Spencer [LLVMdev] LLVM capability question. Reid Spencer [LLVMdev] llvm-gcc frontend 4 on intel darwin produces intel assembler Jakob Praher [LLVMdev] llvm-gcc frontend 4 on intel darwin produces intel assembler Jakob Praher [LLVMdev] llvm-gcc frontend 4 on intel darwin produces intel assembler Tanya M. Lattner [LLVMdev] No crt2.o file found Matthew Bromberg [LLVMdev] Possible bug in the linear scan register allocator Roman Levenstein [LLVMdev] getting process memory info Jakob Praher [LLVMdev] LLVM capability question. Chris Lattner [LLVMdev] No crt2.o file found Anton Korobeynikov [LLVMdev] [patch] arm: external weak in constant pool Chris Lattner [LLVMdev] getting process memory info Ralph Corderoy [LLVMdev] [patch] arm: define extloadi1 Lauro Ramos Venancio [LLVMdev] [patch] arm: define extloadi1 Chris Lattner [LLVMdev] in Cygwin problems Roman [LLVMdev] Possible bug in the linear scan register allocator Chris Lattner [LLVMdev] in Cygwin problems Chris Lattner [LLVMdev] in Cygwin problems Roman [LLVMdev] in Cygwin problems Tanya M. Lattner [LLVMdev] in Cygwin problems Roman [LLVMdev] in Cygwin problems Roman [LLVMdev] Possible bug in the linear scan register allocator Roman Levenstein [LLVMdev] in Cygwin problems Roman [LLVMdev] in Cygwin problems Reid Spencer [LLVMdev] No crt2.o file found SevenThunders [LLVMdev] No crt2.o file found Anton Korobeynikov [LLVMdev] getting process memory info Jakob Praher [LLVMdev] Possible bug in the linear scan register allocator Chris Lattner [LLVMdev] in Cygwin problems Tanya M. Lattner [LLVMdev] [patch] emit .weak for zero initialized weak variables Rafael Espíndola [LLVMdev] Sparse and LLVM Sanghyeon Seo [LLVMdev] Sparse and LLVM Chris Li [LLVMdev] [patch] emit .weak for zero initialized weak variables Rafael Espíndola [LLVMdev] Sparse and LLVM Reid Spencer [LLVMdev] nightly tester grawp Devang Patel [LLVMdev] -s- sriram at malhar.net [LLVMdev] nightly tester grawp Evan Cheng [LLVMdev] nightly tester grawp Reid Spencer [LLVMdev] nightly tester grawp Jim Laskey [LLVMdev] nightly tester grawp Nick Lewycky [LLVMdev] nightly tester grawp Reid Spencer [LLVMdev] nightly tester grawp Reid Spencer [LLVMdev] nightly tester grawp Reid Spencer [LLVMdev] nightly tester grawp Chris Lattner [LLVMdev] nightly tester grawp Reid Spencer [LLVMdev] nightly tester grawp Chris Lattner Last message date: Sun Dec 31 13:37:09 PST 2006 Archived on: Tue Aug 4 17:22:51 PDT 2015 Messages sorted by: [ thread ] [ subject ] [ author ] More info on this list... This archive was generated by Pipermail 0.09 (Mailman edition). | 2026-01-13T09:30:39 |
https://pages.awscloud.com/products/?nc2=h_mo | AWS Support and Customer Service Contact Info | Amazon Web Services Skip to main content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Support › Contact AWS Contact AWS General support for sales, compliance, and subscribers Want to speak with an AWS sales specialist? Get in touch Chat online or talk by phone Connect with support directly Monday through Friday Request form Request AWS sales support Submit a sales support form Compliance support Request support related to AWS compliance Connect with AWS compliance support Subscriber support services Technical support Support for service related technical issues. Unavailable under the Basic Support Plan. Sign in and submit request Account or billing support Assistance with account and billing related inquiries Sign in to request Wrongful charges support Received a bill for AWS, but don't have an AWS account? Learn more Support plans Learn about AWS support plan options See Premium Support options AWS sign-in resources See additional resources for issues related to logging into the console Help signing in to the console Need assistance to sign in to the AWS Management Console? View documentation Trouble shoot your sign-in issue Tried sign in, but the credentials didn’t work? Or don’t have the credentials to access AWS root user account? View solutions Help with multi-factor authentication (MFA) issues Lost or unusable Multi-Factor Authentication (MFA) device View solution Still unable to sign in to your AWS account? If you are still unable to log into your AWS account please fill out this form. View form Additional resources Self-service re:Post provides access to curated knowledge and a vibrant community that helps you become even more successful on AWS View AWS re:Post Service limit increases Need to increase to service limit? Fill out a quick request form Sign in to request Report abuse Report abusive activity from Amazon Web Services Resources Report suspected abuse Amazon.com support Request Kindle or Amazon.com support View on amazon.com Did you find what you were looking for today? Let us know so we can improve the quality of the content on our pages Yes No Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms Cookie Preferences © 2026, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:30:39 |
https://www.facebook.com/sharer/sharer.php?u=https%3a%2f%2fsujaypillai.dev%2f2020%2f08%2f2020-08-21-docker-github-action%2f | Facebook Facebook 이메일 또는 휴대폰 비밀번호 계정을 잊으셨나요? 새 계정 만들기 일시적으로 차단됨 일시적으로 차단됨 회원님의 이 기능 사용 속도가 너무 빠른 것 같습니다. 이 기능 사용에서 일시적으로 차단되었습니다. Back 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch 가입하기 로그인 Messenger Facebook Lite 동영상 Meta Pay Meta 스토어 Meta Quest Ray-Ban Meta Meta AI Meta AI 콘텐츠 더 보기 Instagram Threads 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 Meta © 2026 | 2026-01-13T09:30:39 |
https://www.facebook.com/sharer/sharer.php?u=https%3a%2f%2fsujaypillai.dev%2f2020%2f08%2f2020-08-17-setting-up-blog-on-aws-using-traefik-docker%2f | Facebook Facebook 이메일 또는 휴대폰 비밀번호 계정을 잊으셨나요? 새 계정 만들기 일시적으로 차단됨 일시적으로 차단됨 회원님의 이 기능 사용 속도가 너무 빠른 것 같습니다. 이 기능 사용에서 일시적으로 차단되었습니다. Back 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch 가입하기 로그인 Messenger Facebook Lite 동영상 Meta Pay Meta 스토어 Meta Quest Ray-Ban Meta Meta AI Meta AI 콘텐츠 더 보기 Instagram Threads 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 Meta © 2026 | 2026-01-13T09:30:39 |
https://www.php.net/manual/it/ref.tidy.php | PHP: Tidy Funzioni - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box ob_tidyhandler » « tidyNode::isText Manuale PHP Guida Funzioni Altre estensioni fondamentali Tidy Change language: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other Tidy Funzioni Indice dei contenuti ob_tidyhandler — ob_start callback function to repair the buffer tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document tidy_error_count — Returns the Number of Tidy errors encountered for specified document tidy_get_output — Return a string representing the parsed tidy markup tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document Found A Problem? Learn How To Improve This Page • Submit a Pull Request • Report a Bug + add a note User Contributed Notes 2 notes up down 2 patatraboum at nospam dot fr ¶ 19 years ago <?php // //The tidy tree of your favorite ! //For PHP 5 (CGI) //Thanks to john@php.net // $file = " http://www.php.net " ; // $cns = get_defined_constants ( true ); $tidyCns =array( "tags" =>array(), "types" =>array()); foreach( $cns [ "tidy" ] as $cKey => $cVal ){ if( $cPos = strpos ( $cKey , $cStr = "TAG" )) $tidyCns [ "tags" ][ $cVal ]= " $cStr : " . substr ( $cKey , $cPos + strlen ( $cStr )+ 1 ); elseif( $cPos = strpos ( $cKey , $cStr = "TYPE" )) $tidyCns [ "types" ][ $cVal ]= " $cStr : " . substr ( $cKey , $cPos + strlen ( $cStr )+ 1 ); } $tidyNext =array(); // echo "<html><head><meta http-equiv='Content-Type' content='text/html; charset=windows-1252'><title>Tidy Tree :: $file </title></head>" ; echo "<body><pre>" ; // tidyTree ( tidy_get_root ( tidy_parse_file ( $file )), 0 ); // function tidyTree ( $tidy , $level ){ global $tidyCns , $tidyNext ; $tidyTab =array(); $tidyKeys =array( "type" , "value" , "id" , "attribute" ); foreach( $tidy as $pKey => $pVal ){ if( in_array ( $pKey , $tidyKeys )) $tidyTab [ array_search ( $pKey , $tidyKeys )]= $pVal ; } ksort ( $tidyTab ); foreach( $tidyTab as $pKey => $pVal ){ switch( $pKey ){ case 0 : if( $pVal == 4 ) $value = true ; else $value = false ; echo indent ( true , $level ). $tidyCns [ "types" ][ $pVal ]. "\n" ; break; case 1 : if( $value ){ echo indent ( false , $level ). "VALEUR : " . str_replace ( "\n" , "\n" . indent ( false , $level ), $pVal ). "\n" ; } break; case 2 : echo indent ( false , $level ). $tidyCns [ "tags" ][ $pVal ]. "\n" ; break; case 3 : if( $pVal != NULL ){ echo indent ( false , $level ). "ATTRIBUTS : " ; foreach ( $pVal as $aKey => $aVal ) echo " $aKey = $aVal " ; echo "\n" ; } } } if( $tidy -> hasChildren ()){ $level ++; $i = 0 ; $tidyNext [ $level ]= true ; echo indent ( false , $level ). "\n" ; foreach( $tidy -> child as $child ){ $i ++; if( $i == count ( $tidy -> child )) $tidyNext [ $level ]= false ; tidyTree ( $child , $level ); } } else echo indent ( false , $level ). "\n" ; } // function indent ( $tidyType , $level ){ global $tidyNext ; $indent = "" ; for( $i = 1 ; $i <= $level ; $i ++){ if( $i < $level ||! $tidyType ){ if( $tidyNext [ $i ]) $str = "| " ; else $str = " " ; } else $str = "+--" ; $indent = $indent . $str ; } return $indent ; } // echo "</pre></body></html>" ; // ?> up down 0 bill dot mccuistion at qbopen dot com ¶ 21 years ago Installing tidy on Fedora Core 2 required three libraries: tidy... tidy-devel... libtidy... All of which I found at http://rpm.pbone.net Then, finally, could "./configure --with-tidy" Hope this helps someone out. This was "REALLY" hard (for me) to figure out as no where else was clearly documented. + add a note Tidy Introduzione Installazione/Configurazione Costanti predefinite Esempi tidy tidyNode Tidy Funzioni Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://www.facebook.com/sharer/sharer.php?u=https%3a%2f%2fsujaypillai.dev%2f2020%2f03%2f2020-03-23-first-docker-github-action%2f | Facebook Facebook 이메일 또는 휴대폰 비밀번호 계정을 잊으셨나요? 새 계정 만들기 일시적으로 차단됨 일시적으로 차단됨 회원님의 이 기능 사용 속도가 너무 빠른 것 같습니다. 이 기능 사용에서 일시적으로 차단되었습니다. Back 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch 가입하기 로그인 Messenger Facebook Lite 동영상 Meta Pay Meta 스토어 Meta Quest Ray-Ban Meta Meta AI Meta AI 콘텐츠 더 보기 Instagram Threads 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 Meta © 2026 | 2026-01-13T09:30:39 |
https://www.php.net/x-myracloud-5958a2bbbed300a9b9ac631223924e0b/1768296252.439 | PHP update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box A popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world. What's new in 8.5 Download 8.5.1 · Changelog · Upgrading 8.4.16 · Changelog · Upgrading 8.3.29 · Changelog · Upgrading 8.2.30 · Changelog · Upgrading 18 Dec 2025 PHP 8.1.34 Released! The PHP development team announces the immediate availability of PHP 8.1.34. This is a security release. All PHP 8.1 users are encouraged to upgrade to this version. For source downloads of PHP 8.1.34 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.4.16 Released! The PHP development team announces the immediate availability of PHP 8.4.16. This is a security release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.16 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.2.30 Released! The PHP development team announces the immediate availability of PHP 8.2.30. This is a security release. All PHP 8.2 users are encouraged to upgrade to this version. For source downloads of PHP 8.2.30 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.3.29 Released! The PHP development team announces the immediate availability of PHP 8.3.29. This is a security release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.29 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.5.1 Released! The PHP development team announces the immediate availability of PHP 8.5.1. This is a security release. All PHP 8.5 users are encouraged to upgrade to this version. For source downloads of PHP 8.5.1 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.5.0 Released! The PHP development team announces the immediate availability of PHP 8.5.0. This release marks the latest minor release of the PHP language. PHP 8.5 comes with numerous improvements and new features such as: New "URI" extension New pipe operator (|>) Clone With New #[\NoDiscard] attribute Support for closures, casts, and first class callables in constant expressions And much much more... For source downloads of PHP 8.5.0 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . The migration guide is available in the PHP Manual. Please consult it for the detailed list of new features and backward incompatible changes. Kudos to all the contributors and supporters! 20 Nov 2025 PHP 8.4.15 Released! The PHP development team announces the immediate availability of PHP 8.4.15. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.15 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.3.28 Released! The PHP development team announces the immediate availability of PHP 8.3.28. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.28 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 13 Nov 2025 PHP 8.5.0 RC 5 available for testing The PHP team is pleased to announce the fifth release candidate of PHP 8.5.0, RC 5. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC5, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 06 Nov 2025 PHP 8.5.0 RC4 available for testing The PHP team is pleased to announce the final planned release candidate of PHP 8.5.0, RC 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC4, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 23 Oct 2025 PHP 8.3.27 Released! The PHP development team announces the immediate availability of PHP 8.3.27. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.27 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.4.14 Released! The PHP development team announces the immediate availability of PHP 8.4.14. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.14 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.5.0 RC 3 available for testing The PHP team is pleased to announce the third release candidate of PHP 8.5.0, RC 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC4, planned for 6 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 09 Oct 2025 PHP 8.5.0 RC 2 available for testing The PHP team is pleased to announce the second release candidate of PHP 8.5.0, RC 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC2, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC3, planned for 23 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.5.0 RC 1 available for testing The PHP team is pleased to announce the first release candidate of PHP 8.5.0, RC 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC1, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC2, planned for 9 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.3.26 Released! The PHP development team announces the immediate availability of PHP 8.3.26. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.26 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 25 Sep 2025 PHP 8.4.13 Released! The PHP development team announces the immediate availability of PHP 8.4.13. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.13 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 11 Sep 2025 PHP 8.5.0 Beta 3 available for testing The PHP team is pleased to announce the third beta release of PHP 8.5.0, Beta 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC1, planned for 25 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.5.0 Beta 2 available for testing The PHP team is pleased to announce the second beta release of PHP 8.5.0, Beta 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 2 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 3, planned for 11 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.3.25 Released! The PHP development team announces the immediate availability of PHP 8.3.25. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.25 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 28 Aug 2025 PHP 8.4.12 Released! The PHP development team announces the immediate availability of PHP 8.4.12. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.12 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 14 Aug 2025 PHP 8.5.0 Beta 1 available for testing The PHP team is pleased to announce the first beta release of PHP 8.5.0, Beta 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 1 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 2, planned for 28 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 01 Aug 2025 PHP 8.5.0 Alpha 4 available for testing The PHP team is pleased to announce the third testing release of PHP 8.5.0, Alpha 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Alpha 4 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 1, planned for 14 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 31 Jul 2025 PHP 8.4.11 Released! The PHP development team announces the immediate availability of PHP 8.4.11. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.11 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 31 Jul 2025 PHP 8.3.24 Released! The PHP development team announces the immediate availability of PHP 8.3.24. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.24 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . Older News Entries The PHP Foundation The PHP Foundation is a collective of people and organizations, united in the mission to ensure the long-term prosperity of the PHP language. Donate Upcoming conferences International PHP Conference Berlin 2026 Laravel Live Japan Conferences calling for papers Dutch PHP Conference 2026 User Group Events Special Thanks Social media @official_php @php@fosstodon.org @phpnet Copyright © 2001-2026 The PHP Group My PHP.net Contact Other PHP.net sites Privacy policy View Source ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNode.html#a2479457ae2ca9ae65654ebfb7cb5acaa | LLVM: Node Class Reference LLVM  22.0.0git Public Types | Public Member Functions | Protected Attributes | Friends | List of all members Node Class Reference abstract #include " llvm/Demangle/ItaniumDemangle.h " Inherited by FloatLiteralImpl< float > , FloatLiteralImpl< double > , FloatLiteralImpl< long double > , AbiTagAttr , ArraySubscriptExpr , ArrayType , BinaryExpr , BinaryFPType , BitIntType , BoolExpr , BracedExpr , BracedRangeExpr , CallExpr , CastExpr , ClosureTypeName , ConditionalExpr , ConstrainedTypeTemplateParamDecl , ConversionExpr , ConversionOperatorType , CtorDtorName , CtorVtableSpecialName , DeleteExpr , DotSuffix , DtorName , DynamicExceptionSpec , ElaboratedTypeSpefType , EnableIfAttr , EnclosingExpr , EnumLiteral , ExpandedSpecialSubstitution , ExplicitObjectParameter , ExprRequirement , FloatLiteralImpl< Float > , FoldExpr , ForwardTemplateReference , FunctionEncoding , FunctionParam , FunctionType , GlobalQualifiedName , InitListExpr , IntegerLiteral , LambdaExpr , LiteralOperator , LocalName , MemberExpr , MemberLikeFriendName , ModuleEntity , ModuleName , NameType , NameWithTemplateArgs , NestedName , NestedRequirement , NewExpr , NodeArrayNode , NoexceptSpec , NonTypeTemplateParamDecl , ObjCProtoName , ParameterPack , ParameterPackExpansion , PixelVectorType , PointerToMemberConversionExpr , PointerToMemberType , PointerType , PostfixExpr , PostfixQualifiedType , PrefixExpr , QualType , QualifiedName , ReferenceType , RequiresExpr , SizeofParamPackExpr , SpecialName , StringLiteral , StructuredBindingName , SubobjectExpr , SyntheticTemplateParamName , TemplateArgs , TemplateArgumentPack , TemplateParamPackDecl , TemplateParamQualifiedArg , TemplateTemplateParamDecl , ThrowExpr , TransformedType , TypeRequirement , TypeTemplateParamDecl , UnnamedTypeName , VectorType , and VendorExtQualType . Public Types enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Public Member Functions   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Protected Attributes Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Friends class  OutputBuffer Detailed Description Definition at line 166 of file ItaniumDemangle.h . Member Enumeration Documentation ◆  Cache enum class Node::Cache : uint8_t strong Three-way bool to track a cached value. Unknown is possible if this node has an unexpanded parameter pack below it that may affect this cache. Enumerator Yes  No  Unknown  Definition at line 175 of file ItaniumDemangle.h . ◆  Kind enum Node::Kind : uint8_t Definition at line 168 of file ItaniumDemangle.h . ◆  Prec enum class Node::Prec : uint8_t strong Operator precedence for expression nodes. Used to determine required parens in expression emission. Enumerator Primary  Postfix  Unary  Cast  PtrMem  Multiplicative  Additive  Shift  Spaceship  Relational  Equality  And  Xor  Ior  AndIf  OrIf  Conditional  Assign  Comma  Default  Definition at line 179 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  Node() [1/2] Node::Node ( Kind K_ , Prec Precedence_ = Prec::Primary , Cache RHSComponentCache_ = Cache::No , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 221 of file ItaniumDemangle.h . References ArrayCache , FunctionCache , No , Primary , and RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , ArraySubscriptExpr::ArraySubscriptExpr() , ArrayType::ArrayType() , BinaryExpr::BinaryExpr() , BinaryFPType::BinaryFPType() , BitIntType::BitIntType() , BoolExpr::BoolExpr() , BracedExpr::BracedExpr() , BracedRangeExpr::BracedRangeExpr() , CallExpr::CallExpr() , CastExpr::CastExpr() , ClosureTypeName::ClosureTypeName() , ConditionalExpr::ConditionalExpr() , ConstrainedTypeTemplateParamDecl::ConstrainedTypeTemplateParamDecl() , ConversionExpr::ConversionExpr() , ConversionOperatorType::ConversionOperatorType() , CtorDtorName::CtorDtorName() , CtorVtableSpecialName::CtorVtableSpecialName() , DeleteExpr::DeleteExpr() , DotSuffix::DotSuffix() , DtorName::DtorName() , DynamicExceptionSpec::DynamicExceptionSpec() , ElaboratedTypeSpefType::ElaboratedTypeSpefType() , EnableIfAttr::EnableIfAttr() , EnclosingExpr::EnclosingExpr() , EnumLiteral::EnumLiteral() , ExpandedSpecialSubstitution::ExpandedSpecialSubstitution() , ExplicitObjectParameter::ExplicitObjectParameter() , ExprRequirement::ExprRequirement() , FloatLiteralImpl< float >::FloatLiteralImpl() , FoldExpr::FoldExpr() , ForwardTemplateReference::ForwardTemplateReference() , FunctionEncoding::FunctionEncoding() , FunctionParam::FunctionParam() , FunctionType::FunctionType() , TemplateParamQualifiedArg::getArg() , FunctionEncoding::getAttrs() , VectorType::getBaseType() , ParameterPackExpansion::getChild() , QualType::getChild() , VectorType::getDimension() , FunctionEncoding::getName() , PointerType::getPointee() , FunctionEncoding::getRequires() , FunctionEncoding::getReturnType() , ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , VendorExtQualType::getTA() , VendorExtQualType::getTy() , GlobalQualifiedName::GlobalQualifiedName() , InitListExpr::InitListExpr() , IntegerLiteral::IntegerLiteral() , LambdaExpr::LambdaExpr() , LiteralOperator::LiteralOperator() , LocalName::LocalName() , MemberExpr::MemberExpr() , MemberLikeFriendName::MemberLikeFriendName() , ModuleEntity::ModuleEntity() , ModuleName::ModuleName() , NameType::NameType() , NameWithTemplateArgs::NameWithTemplateArgs() , NestedName::NestedName() , NestedRequirement::NestedRequirement() , NewExpr::NewExpr() , Node() , NodeArrayNode::NodeArrayNode() , NoexceptSpec::NoexceptSpec() , NonTypeTemplateParamDecl::NonTypeTemplateParamDecl() , ObjCProtoName::ObjCProtoName() , ParameterPack::ParameterPack() , ParameterPackExpansion::ParameterPackExpansion() , PixelVectorType::PixelVectorType() , PointerToMemberConversionExpr::PointerToMemberConversionExpr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , PostfixExpr::PostfixExpr() , PostfixQualifiedType::PostfixQualifiedType() , PrefixExpr::PrefixExpr() , RequiresExpr::printLeft() , QualifiedName::QualifiedName() , QualType::QualType() , ReferenceType::ReferenceType() , RequiresExpr::RequiresExpr() , SizeofParamPackExpr::SizeofParamPackExpr() , SpecialName::SpecialName() , StringLiteral::StringLiteral() , StructuredBindingName::StructuredBindingName() , SubobjectExpr::SubobjectExpr() , SyntheticTemplateParamName::SyntheticTemplateParamName() , TemplateArgs::TemplateArgs() , TemplateArgumentPack::TemplateArgumentPack() , TemplateParamPackDecl::TemplateParamPackDecl() , TemplateParamQualifiedArg::TemplateParamQualifiedArg() , TemplateTemplateParamDecl::TemplateTemplateParamDecl() , ThrowExpr::ThrowExpr() , TransformedType::TransformedType() , TypeRequirement::TypeRequirement() , TypeTemplateParamDecl::TypeTemplateParamDecl() , UnnamedTypeName::UnnamedTypeName() , VectorType::VectorType() , and VendorExtQualType::VendorExtQualType() . ◆  Node() [2/2] Node::Node ( Kind K_ , Cache RHSComponentCache_ , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 226 of file ItaniumDemangle.h . References No , Node() , and Primary . ◆  ~Node() virtual Node::~Node ( ) virtual default Member Function Documentation ◆  dump() DEMANGLE_DUMP_METHOD void Node::dump ( ) const References DEMANGLE_DUMP_METHOD . Referenced by llvm::DAGTypeLegalizer::run() , and llvm::RISCVDAGToDAGISel::Select() . ◆  getArrayCache() Cache Node::getArrayCache ( ) const inline Definition at line 262 of file ItaniumDemangle.h . References ArrayCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getBaseName() virtual std::string_view Node::getBaseName ( ) const inline virtual Reimplemented in AbiTagAttr , ExpandedSpecialSubstitution , GlobalQualifiedName , MemberLikeFriendName , ModuleEntity , NameType , NameWithTemplateArgs , NestedName , QualifiedName , and SpecialSubstitution . Definition at line 299 of file ItaniumDemangle.h . ◆  getFunctionCache() Cache Node::getFunctionCache ( ) const inline Definition at line 263 of file ItaniumDemangle.h . References FunctionCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getKind() Kind Node::getKind ( ) const inline Definition at line 258 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseCtorDtorName() , AbstractManglingParser< Derived, Alloc >::parseNestedName() , AbstractManglingParser< Derived, Alloc >::parseTemplateArgs() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnscopedName() , NodeArray::printAsString() , and llvm::msgpack::Document::writeToBlob() . ◆  getPrecedence() Prec Node::getPrecedence ( ) const inline Definition at line 260 of file ItaniumDemangle.h . Referenced by ArraySubscriptExpr::match() , BinaryExpr::match() , CallExpr::match() , CastExpr::match() , ConditionalExpr::match() , ConversionExpr::match() , DeleteExpr::match() , EnclosingExpr::match() , MemberExpr::match() , NewExpr::match() , PointerToMemberConversionExpr::match() , PostfixExpr::match() , PrefixExpr::match() , printAsOperand() , ArraySubscriptExpr::printLeft() , BinaryExpr::printLeft() , ConditionalExpr::printLeft() , MemberExpr::printLeft() , PostfixExpr::printLeft() , and PrefixExpr::printLeft() . ◆  getRHSComponentCache() Cache Node::getRHSComponentCache ( ) const inline Definition at line 261 of file ItaniumDemangle.h . References RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , QualType::QualType() , and ReferenceType::ReferenceType() . ◆  getSyntaxNode() virtual const Node * Node::getSyntaxNode ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , and ParameterPack . Definition at line 271 of file ItaniumDemangle.h . References Node() , and OutputBuffer . ◆  hasArray() bool Node::hasArray ( OutputBuffer & OB ) const inline Definition at line 246 of file ItaniumDemangle.h . References ArrayCache , hasArraySlow() , OutputBuffer , Unknown , and Yes . ◆  hasArraySlow() virtual bool Node::hasArraySlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , ParameterPack , and QualType . Definition at line 266 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasArray() . ◆  hasFunction() bool Node::hasFunction ( OutputBuffer & OB ) const inline Definition at line 252 of file ItaniumDemangle.h . References FunctionCache , hasFunctionSlow() , OutputBuffer , Unknown , and Yes . ◆  hasFunctionSlow() virtual bool Node::hasFunctionSlow ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , and QualType . Definition at line 267 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasFunction() . ◆  hasRHSComponent() bool Node::hasRHSComponent ( OutputBuffer & OB ) const inline Definition at line 240 of file ItaniumDemangle.h . References hasRHSComponentSlow() , OutputBuffer , RHSComponentCache , Unknown , and Yes . ◆  hasRHSComponentSlow() virtual bool Node::hasRHSComponentSlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , PointerToMemberType , PointerType , QualType , and ReferenceType . Definition at line 265 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasRHSComponent() . ◆  print() void Node::print ( OutputBuffer & OB ) const inline Definition at line 286 of file ItaniumDemangle.h . References No , OutputBuffer , and RHSComponentCache . Referenced by llvm::ItaniumPartialDemangler::getFunctionDeclContextName() , llvm::DOTGraphTraits< AADepGraph * >::getNodeLabel() , llvm::DOTGraphTraits< const MachineFunction * >::getNodeLabel() , llvm::itaniumDemangle() , printAsOperand() , FoldExpr::printLeft() , and printNode() . ◆  printAsOperand() void Node::printAsOperand ( OutputBuffer & OB , Prec P = Prec::Default , bool StrictlyWorse = false  ) const inline Definition at line 275 of file ItaniumDemangle.h . References Default , getPrecedence() , OutputBuffer , P , and print() . Referenced by llvm::DOTGraphTraits< DOTFuncInfo * >::getBBName() , getSimpleNodeName() , llvm::operator<<() , llvm::VPIRMetadata::print() , and llvm::SimpleNodeLabelString() . ◆  printInitListAsType() virtual bool Node::printInitListAsType ( OutputBuffer & , const NodeArray &  ) const inline virtual Reimplemented in ArrayType . Definition at line 295 of file ItaniumDemangle.h . References OutputBuffer . ◆  visit() template<typename Fn> void Node::visit ( Fn F ) const Visit the most-derived object corresponding to this object. Visit the node. Calls F(P) , where P is the node cast to the appropriate derived class. Definition at line 2639 of file ItaniumDemangle.h . References DEMANGLE_ASSERT , and F . Friends And Related Symbol Documentation ◆  OutputBuffer friend class OutputBuffer friend Definition at line 309 of file ItaniumDemangle.h . References OutputBuffer . Referenced by ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , hasArray() , ArrayType::hasArraySlow() , ForwardTemplateReference::hasArraySlow() , hasArraySlow() , ParameterPack::hasArraySlow() , QualType::hasArraySlow() , hasFunction() , ForwardTemplateReference::hasFunctionSlow() , FunctionEncoding::hasFunctionSlow() , FunctionType::hasFunctionSlow() , hasFunctionSlow() , ParameterPack::hasFunctionSlow() , QualType::hasFunctionSlow() , hasRHSComponent() , ArrayType::hasRHSComponentSlow() , ForwardTemplateReference::hasRHSComponentSlow() , FunctionEncoding::hasRHSComponentSlow() , FunctionType::hasRHSComponentSlow() , hasRHSComponentSlow() , ParameterPack::hasRHSComponentSlow() , PointerToMemberType::hasRHSComponentSlow() , PointerType::hasRHSComponentSlow() , QualType::hasRHSComponentSlow() , ReferenceType::hasRHSComponentSlow() , OutputBuffer , print() , printAsOperand() , ClosureTypeName::printDeclarator() , ArrayType::printInitListAsType() , printInitListAsType() , AbiTagAttr::printLeft() , ArraySubscriptExpr::printLeft() , ArrayType::printLeft() , BinaryExpr::printLeft() , BinaryFPType::printLeft() , BitIntType::printLeft() , BoolExpr::printLeft() , BracedExpr::printLeft() , BracedRangeExpr::printLeft() , CallExpr::printLeft() , CastExpr::printLeft() , ClosureTypeName::printLeft() , ConditionalExpr::printLeft() , ConstrainedTypeTemplateParamDecl::printLeft() , ConversionExpr::printLeft() , ConversionOperatorType::printLeft() , CtorDtorName::printLeft() , CtorVtableSpecialName::printLeft() , DeleteExpr::printLeft() , DotSuffix::printLeft() , DtorName::printLeft() , DynamicExceptionSpec::printLeft() , ElaboratedTypeSpefType::printLeft() , EnableIfAttr::printLeft() , EnclosingExpr::printLeft() , EnumLiteral::printLeft() , ExplicitObjectParameter::printLeft() , ExprRequirement::printLeft() , FloatLiteralImpl< float >::printLeft() , FoldExpr::printLeft() , ForwardTemplateReference::printLeft() , FunctionEncoding::printLeft() , FunctionParam::printLeft() , FunctionType::printLeft() , GlobalQualifiedName::printLeft() , InitListExpr::printLeft() , IntegerLiteral::printLeft() , LambdaExpr::printLeft() , LiteralOperator::printLeft() , LocalName::printLeft() , MemberExpr::printLeft() , MemberLikeFriendName::printLeft() , ModuleEntity::printLeft() , ModuleName::printLeft() , NameType::printLeft() , NameWithTemplateArgs::printLeft() , NestedName::printLeft() , NestedRequirement::printLeft() , NewExpr::printLeft() , NodeArrayNode::printLeft() , NoexceptSpec::printLeft() , NonTypeTemplateParamDecl::printLeft() , ObjCProtoName::printLeft() , ParameterPack::printLeft() , ParameterPackExpansion::printLeft() , PixelVectorType::printLeft() , PointerToMemberConversionExpr::printLeft() , PointerToMemberType::printLeft() , PointerType::printLeft() , PostfixExpr::printLeft() , PostfixQualifiedType::printLeft() , PrefixExpr::printLeft() , QualifiedName::printLeft() , QualType::printLeft() , ReferenceType::printLeft() , RequiresExpr::printLeft() , SizeofParamPackExpr::printLeft() , SpecialName::printLeft() , SpecialSubstitution::printLeft() , StringLiteral::printLeft() , StructuredBindingName::printLeft() , SubobjectExpr::printLeft() , SyntheticTemplateParamName::printLeft() , TemplateArgs::printLeft() , TemplateArgumentPack::printLeft() , TemplateParamPackDecl::printLeft() , TemplateParamQualifiedArg::printLeft() , TemplateTemplateParamDecl::printLeft() , ThrowExpr::printLeft() , TransformedType::printLeft() , TypeRequirement::printLeft() , TypeTemplateParamDecl::printLeft() , UnnamedTypeName::printLeft() , VectorType::printLeft() , VendorExtQualType::printLeft() , QualType::printQuals() , ArrayType::printRight() , ConstrainedTypeTemplateParamDecl::printRight() , ForwardTemplateReference::printRight() , FunctionEncoding::printRight() , FunctionType::printRight() , NonTypeTemplateParamDecl::printRight() , ParameterPack::printRight() , PointerToMemberType::printRight() , PointerType::printRight() , QualType::printRight() , ReferenceType::printRight() , TemplateParamPackDecl::printRight() , TemplateTemplateParamDecl::printRight() , and TypeTemplateParamDecl::printRight() . Member Data Documentation ◆  ArrayCache Cache Node::ArrayCache protected Track if this node is a (possibly qualified) array type. This can affect how we format the output string. Definition at line 214 of file ItaniumDemangle.h . Referenced by getArrayCache() , hasArray() , Node() , and ParameterPack::ParameterPack() . ◆  FunctionCache Cache Node::FunctionCache protected Track if this node is a (possibly qualified) function type. This can affect how we format the output string. Definition at line 218 of file ItaniumDemangle.h . Referenced by getFunctionCache() , hasFunction() , Node() , and ParameterPack::ParameterPack() . ◆  RHSComponentCache Cache Node::RHSComponentCache protected Tracks if this node has a component on its right side, in which case we need to call printRight. Definition at line 210 of file ItaniumDemangle.h . Referenced by getRHSComponentCache() , hasRHSComponent() , Node() , ParameterPack::ParameterPack() , and print() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://www.facebook.com/timeforkids | Facebook Facebook 이메일 또는 휴대폰 비밀번호 계정을 잊으셨나요? 새 계정 만들기 일시적으로 차단됨 일시적으로 차단됨 회원님의 이 기능 사용 속도가 너무 빠른 것 같습니다. 이 기능 사용에서 일시적으로 차단되었습니다. Back 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch 가입하기 로그인 Messenger Facebook Lite 동영상 Meta Pay Meta 스토어 Meta Quest Ray-Ban Meta Meta AI Meta AI 콘텐츠 더 보기 Instagram Threads 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 Meta © 2026 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNode.html#a71e83c2fb7c7ebff21c7e44eaa393655abafd7322c6e97d25b6299b5d6fe8920b | LLVM: Node Class Reference LLVM  22.0.0git Public Types | Public Member Functions | Protected Attributes | Friends | List of all members Node Class Reference abstract #include " llvm/Demangle/ItaniumDemangle.h " Inherited by FloatLiteralImpl< float > , FloatLiteralImpl< double > , FloatLiteralImpl< long double > , AbiTagAttr , ArraySubscriptExpr , ArrayType , BinaryExpr , BinaryFPType , BitIntType , BoolExpr , BracedExpr , BracedRangeExpr , CallExpr , CastExpr , ClosureTypeName , ConditionalExpr , ConstrainedTypeTemplateParamDecl , ConversionExpr , ConversionOperatorType , CtorDtorName , CtorVtableSpecialName , DeleteExpr , DotSuffix , DtorName , DynamicExceptionSpec , ElaboratedTypeSpefType , EnableIfAttr , EnclosingExpr , EnumLiteral , ExpandedSpecialSubstitution , ExplicitObjectParameter , ExprRequirement , FloatLiteralImpl< Float > , FoldExpr , ForwardTemplateReference , FunctionEncoding , FunctionParam , FunctionType , GlobalQualifiedName , InitListExpr , IntegerLiteral , LambdaExpr , LiteralOperator , LocalName , MemberExpr , MemberLikeFriendName , ModuleEntity , ModuleName , NameType , NameWithTemplateArgs , NestedName , NestedRequirement , NewExpr , NodeArrayNode , NoexceptSpec , NonTypeTemplateParamDecl , ObjCProtoName , ParameterPack , ParameterPackExpansion , PixelVectorType , PointerToMemberConversionExpr , PointerToMemberType , PointerType , PostfixExpr , PostfixQualifiedType , PrefixExpr , QualType , QualifiedName , ReferenceType , RequiresExpr , SizeofParamPackExpr , SpecialName , StringLiteral , StructuredBindingName , SubobjectExpr , SyntheticTemplateParamName , TemplateArgs , TemplateArgumentPack , TemplateParamPackDecl , TemplateParamQualifiedArg , TemplateTemplateParamDecl , ThrowExpr , TransformedType , TypeRequirement , TypeTemplateParamDecl , UnnamedTypeName , VectorType , and VendorExtQualType . Public Types enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Public Member Functions   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Protected Attributes Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Friends class  OutputBuffer Detailed Description Definition at line 166 of file ItaniumDemangle.h . Member Enumeration Documentation ◆  Cache enum class Node::Cache : uint8_t strong Three-way bool to track a cached value. Unknown is possible if this node has an unexpanded parameter pack below it that may affect this cache. Enumerator Yes  No  Unknown  Definition at line 175 of file ItaniumDemangle.h . ◆  Kind enum Node::Kind : uint8_t Definition at line 168 of file ItaniumDemangle.h . ◆  Prec enum class Node::Prec : uint8_t strong Operator precedence for expression nodes. Used to determine required parens in expression emission. Enumerator Primary  Postfix  Unary  Cast  PtrMem  Multiplicative  Additive  Shift  Spaceship  Relational  Equality  And  Xor  Ior  AndIf  OrIf  Conditional  Assign  Comma  Default  Definition at line 179 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  Node() [1/2] Node::Node ( Kind K_ , Prec Precedence_ = Prec::Primary , Cache RHSComponentCache_ = Cache::No , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 221 of file ItaniumDemangle.h . References ArrayCache , FunctionCache , No , Primary , and RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , ArraySubscriptExpr::ArraySubscriptExpr() , ArrayType::ArrayType() , BinaryExpr::BinaryExpr() , BinaryFPType::BinaryFPType() , BitIntType::BitIntType() , BoolExpr::BoolExpr() , BracedExpr::BracedExpr() , BracedRangeExpr::BracedRangeExpr() , CallExpr::CallExpr() , CastExpr::CastExpr() , ClosureTypeName::ClosureTypeName() , ConditionalExpr::ConditionalExpr() , ConstrainedTypeTemplateParamDecl::ConstrainedTypeTemplateParamDecl() , ConversionExpr::ConversionExpr() , ConversionOperatorType::ConversionOperatorType() , CtorDtorName::CtorDtorName() , CtorVtableSpecialName::CtorVtableSpecialName() , DeleteExpr::DeleteExpr() , DotSuffix::DotSuffix() , DtorName::DtorName() , DynamicExceptionSpec::DynamicExceptionSpec() , ElaboratedTypeSpefType::ElaboratedTypeSpefType() , EnableIfAttr::EnableIfAttr() , EnclosingExpr::EnclosingExpr() , EnumLiteral::EnumLiteral() , ExpandedSpecialSubstitution::ExpandedSpecialSubstitution() , ExplicitObjectParameter::ExplicitObjectParameter() , ExprRequirement::ExprRequirement() , FloatLiteralImpl< float >::FloatLiteralImpl() , FoldExpr::FoldExpr() , ForwardTemplateReference::ForwardTemplateReference() , FunctionEncoding::FunctionEncoding() , FunctionParam::FunctionParam() , FunctionType::FunctionType() , TemplateParamQualifiedArg::getArg() , FunctionEncoding::getAttrs() , VectorType::getBaseType() , ParameterPackExpansion::getChild() , QualType::getChild() , VectorType::getDimension() , FunctionEncoding::getName() , PointerType::getPointee() , FunctionEncoding::getRequires() , FunctionEncoding::getReturnType() , ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , VendorExtQualType::getTA() , VendorExtQualType::getTy() , GlobalQualifiedName::GlobalQualifiedName() , InitListExpr::InitListExpr() , IntegerLiteral::IntegerLiteral() , LambdaExpr::LambdaExpr() , LiteralOperator::LiteralOperator() , LocalName::LocalName() , MemberExpr::MemberExpr() , MemberLikeFriendName::MemberLikeFriendName() , ModuleEntity::ModuleEntity() , ModuleName::ModuleName() , NameType::NameType() , NameWithTemplateArgs::NameWithTemplateArgs() , NestedName::NestedName() , NestedRequirement::NestedRequirement() , NewExpr::NewExpr() , Node() , NodeArrayNode::NodeArrayNode() , NoexceptSpec::NoexceptSpec() , NonTypeTemplateParamDecl::NonTypeTemplateParamDecl() , ObjCProtoName::ObjCProtoName() , ParameterPack::ParameterPack() , ParameterPackExpansion::ParameterPackExpansion() , PixelVectorType::PixelVectorType() , PointerToMemberConversionExpr::PointerToMemberConversionExpr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , PostfixExpr::PostfixExpr() , PostfixQualifiedType::PostfixQualifiedType() , PrefixExpr::PrefixExpr() , RequiresExpr::printLeft() , QualifiedName::QualifiedName() , QualType::QualType() , ReferenceType::ReferenceType() , RequiresExpr::RequiresExpr() , SizeofParamPackExpr::SizeofParamPackExpr() , SpecialName::SpecialName() , StringLiteral::StringLiteral() , StructuredBindingName::StructuredBindingName() , SubobjectExpr::SubobjectExpr() , SyntheticTemplateParamName::SyntheticTemplateParamName() , TemplateArgs::TemplateArgs() , TemplateArgumentPack::TemplateArgumentPack() , TemplateParamPackDecl::TemplateParamPackDecl() , TemplateParamQualifiedArg::TemplateParamQualifiedArg() , TemplateTemplateParamDecl::TemplateTemplateParamDecl() , ThrowExpr::ThrowExpr() , TransformedType::TransformedType() , TypeRequirement::TypeRequirement() , TypeTemplateParamDecl::TypeTemplateParamDecl() , UnnamedTypeName::UnnamedTypeName() , VectorType::VectorType() , and VendorExtQualType::VendorExtQualType() . ◆  Node() [2/2] Node::Node ( Kind K_ , Cache RHSComponentCache_ , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 226 of file ItaniumDemangle.h . References No , Node() , and Primary . ◆  ~Node() virtual Node::~Node ( ) virtual default Member Function Documentation ◆  dump() DEMANGLE_DUMP_METHOD void Node::dump ( ) const References DEMANGLE_DUMP_METHOD . Referenced by llvm::DAGTypeLegalizer::run() , and llvm::RISCVDAGToDAGISel::Select() . ◆  getArrayCache() Cache Node::getArrayCache ( ) const inline Definition at line 262 of file ItaniumDemangle.h . References ArrayCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getBaseName() virtual std::string_view Node::getBaseName ( ) const inline virtual Reimplemented in AbiTagAttr , ExpandedSpecialSubstitution , GlobalQualifiedName , MemberLikeFriendName , ModuleEntity , NameType , NameWithTemplateArgs , NestedName , QualifiedName , and SpecialSubstitution . Definition at line 299 of file ItaniumDemangle.h . ◆  getFunctionCache() Cache Node::getFunctionCache ( ) const inline Definition at line 263 of file ItaniumDemangle.h . References FunctionCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getKind() Kind Node::getKind ( ) const inline Definition at line 258 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseCtorDtorName() , AbstractManglingParser< Derived, Alloc >::parseNestedName() , AbstractManglingParser< Derived, Alloc >::parseTemplateArgs() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnscopedName() , NodeArray::printAsString() , and llvm::msgpack::Document::writeToBlob() . ◆  getPrecedence() Prec Node::getPrecedence ( ) const inline Definition at line 260 of file ItaniumDemangle.h . Referenced by ArraySubscriptExpr::match() , BinaryExpr::match() , CallExpr::match() , CastExpr::match() , ConditionalExpr::match() , ConversionExpr::match() , DeleteExpr::match() , EnclosingExpr::match() , MemberExpr::match() , NewExpr::match() , PointerToMemberConversionExpr::match() , PostfixExpr::match() , PrefixExpr::match() , printAsOperand() , ArraySubscriptExpr::printLeft() , BinaryExpr::printLeft() , ConditionalExpr::printLeft() , MemberExpr::printLeft() , PostfixExpr::printLeft() , and PrefixExpr::printLeft() . ◆  getRHSComponentCache() Cache Node::getRHSComponentCache ( ) const inline Definition at line 261 of file ItaniumDemangle.h . References RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , QualType::QualType() , and ReferenceType::ReferenceType() . ◆  getSyntaxNode() virtual const Node * Node::getSyntaxNode ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , and ParameterPack . Definition at line 271 of file ItaniumDemangle.h . References Node() , and OutputBuffer . ◆  hasArray() bool Node::hasArray ( OutputBuffer & OB ) const inline Definition at line 246 of file ItaniumDemangle.h . References ArrayCache , hasArraySlow() , OutputBuffer , Unknown , and Yes . ◆  hasArraySlow() virtual bool Node::hasArraySlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , ParameterPack , and QualType . Definition at line 266 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasArray() . ◆  hasFunction() bool Node::hasFunction ( OutputBuffer & OB ) const inline Definition at line 252 of file ItaniumDemangle.h . References FunctionCache , hasFunctionSlow() , OutputBuffer , Unknown , and Yes . ◆  hasFunctionSlow() virtual bool Node::hasFunctionSlow ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , and QualType . Definition at line 267 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasFunction() . ◆  hasRHSComponent() bool Node::hasRHSComponent ( OutputBuffer & OB ) const inline Definition at line 240 of file ItaniumDemangle.h . References hasRHSComponentSlow() , OutputBuffer , RHSComponentCache , Unknown , and Yes . ◆  hasRHSComponentSlow() virtual bool Node::hasRHSComponentSlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , PointerToMemberType , PointerType , QualType , and ReferenceType . Definition at line 265 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasRHSComponent() . ◆  print() void Node::print ( OutputBuffer & OB ) const inline Definition at line 286 of file ItaniumDemangle.h . References No , OutputBuffer , and RHSComponentCache . Referenced by llvm::ItaniumPartialDemangler::getFunctionDeclContextName() , llvm::DOTGraphTraits< AADepGraph * >::getNodeLabel() , llvm::DOTGraphTraits< const MachineFunction * >::getNodeLabel() , llvm::itaniumDemangle() , printAsOperand() , FoldExpr::printLeft() , and printNode() . ◆  printAsOperand() void Node::printAsOperand ( OutputBuffer & OB , Prec P = Prec::Default , bool StrictlyWorse = false  ) const inline Definition at line 275 of file ItaniumDemangle.h . References Default , getPrecedence() , OutputBuffer , P , and print() . Referenced by llvm::DOTGraphTraits< DOTFuncInfo * >::getBBName() , getSimpleNodeName() , llvm::operator<<() , llvm::VPIRMetadata::print() , and llvm::SimpleNodeLabelString() . ◆  printInitListAsType() virtual bool Node::printInitListAsType ( OutputBuffer & , const NodeArray &  ) const inline virtual Reimplemented in ArrayType . Definition at line 295 of file ItaniumDemangle.h . References OutputBuffer . ◆  visit() template<typename Fn> void Node::visit ( Fn F ) const Visit the most-derived object corresponding to this object. Visit the node. Calls F(P) , where P is the node cast to the appropriate derived class. Definition at line 2639 of file ItaniumDemangle.h . References DEMANGLE_ASSERT , and F . Friends And Related Symbol Documentation ◆  OutputBuffer friend class OutputBuffer friend Definition at line 309 of file ItaniumDemangle.h . References OutputBuffer . Referenced by ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , hasArray() , ArrayType::hasArraySlow() , ForwardTemplateReference::hasArraySlow() , hasArraySlow() , ParameterPack::hasArraySlow() , QualType::hasArraySlow() , hasFunction() , ForwardTemplateReference::hasFunctionSlow() , FunctionEncoding::hasFunctionSlow() , FunctionType::hasFunctionSlow() , hasFunctionSlow() , ParameterPack::hasFunctionSlow() , QualType::hasFunctionSlow() , hasRHSComponent() , ArrayType::hasRHSComponentSlow() , ForwardTemplateReference::hasRHSComponentSlow() , FunctionEncoding::hasRHSComponentSlow() , FunctionType::hasRHSComponentSlow() , hasRHSComponentSlow() , ParameterPack::hasRHSComponentSlow() , PointerToMemberType::hasRHSComponentSlow() , PointerType::hasRHSComponentSlow() , QualType::hasRHSComponentSlow() , ReferenceType::hasRHSComponentSlow() , OutputBuffer , print() , printAsOperand() , ClosureTypeName::printDeclarator() , ArrayType::printInitListAsType() , printInitListAsType() , AbiTagAttr::printLeft() , ArraySubscriptExpr::printLeft() , ArrayType::printLeft() , BinaryExpr::printLeft() , BinaryFPType::printLeft() , BitIntType::printLeft() , BoolExpr::printLeft() , BracedExpr::printLeft() , BracedRangeExpr::printLeft() , CallExpr::printLeft() , CastExpr::printLeft() , ClosureTypeName::printLeft() , ConditionalExpr::printLeft() , ConstrainedTypeTemplateParamDecl::printLeft() , ConversionExpr::printLeft() , ConversionOperatorType::printLeft() , CtorDtorName::printLeft() , CtorVtableSpecialName::printLeft() , DeleteExpr::printLeft() , DotSuffix::printLeft() , DtorName::printLeft() , DynamicExceptionSpec::printLeft() , ElaboratedTypeSpefType::printLeft() , EnableIfAttr::printLeft() , EnclosingExpr::printLeft() , EnumLiteral::printLeft() , ExplicitObjectParameter::printLeft() , ExprRequirement::printLeft() , FloatLiteralImpl< float >::printLeft() , FoldExpr::printLeft() , ForwardTemplateReference::printLeft() , FunctionEncoding::printLeft() , FunctionParam::printLeft() , FunctionType::printLeft() , GlobalQualifiedName::printLeft() , InitListExpr::printLeft() , IntegerLiteral::printLeft() , LambdaExpr::printLeft() , LiteralOperator::printLeft() , LocalName::printLeft() , MemberExpr::printLeft() , MemberLikeFriendName::printLeft() , ModuleEntity::printLeft() , ModuleName::printLeft() , NameType::printLeft() , NameWithTemplateArgs::printLeft() , NestedName::printLeft() , NestedRequirement::printLeft() , NewExpr::printLeft() , NodeArrayNode::printLeft() , NoexceptSpec::printLeft() , NonTypeTemplateParamDecl::printLeft() , ObjCProtoName::printLeft() , ParameterPack::printLeft() , ParameterPackExpansion::printLeft() , PixelVectorType::printLeft() , PointerToMemberConversionExpr::printLeft() , PointerToMemberType::printLeft() , PointerType::printLeft() , PostfixExpr::printLeft() , PostfixQualifiedType::printLeft() , PrefixExpr::printLeft() , QualifiedName::printLeft() , QualType::printLeft() , ReferenceType::printLeft() , RequiresExpr::printLeft() , SizeofParamPackExpr::printLeft() , SpecialName::printLeft() , SpecialSubstitution::printLeft() , StringLiteral::printLeft() , StructuredBindingName::printLeft() , SubobjectExpr::printLeft() , SyntheticTemplateParamName::printLeft() , TemplateArgs::printLeft() , TemplateArgumentPack::printLeft() , TemplateParamPackDecl::printLeft() , TemplateParamQualifiedArg::printLeft() , TemplateTemplateParamDecl::printLeft() , ThrowExpr::printLeft() , TransformedType::printLeft() , TypeRequirement::printLeft() , TypeTemplateParamDecl::printLeft() , UnnamedTypeName::printLeft() , VectorType::printLeft() , VendorExtQualType::printLeft() , QualType::printQuals() , ArrayType::printRight() , ConstrainedTypeTemplateParamDecl::printRight() , ForwardTemplateReference::printRight() , FunctionEncoding::printRight() , FunctionType::printRight() , NonTypeTemplateParamDecl::printRight() , ParameterPack::printRight() , PointerToMemberType::printRight() , PointerType::printRight() , QualType::printRight() , ReferenceType::printRight() , TemplateParamPackDecl::printRight() , TemplateTemplateParamDecl::printRight() , and TypeTemplateParamDecl::printRight() . Member Data Documentation ◆  ArrayCache Cache Node::ArrayCache protected Track if this node is a (possibly qualified) array type. This can affect how we format the output string. Definition at line 214 of file ItaniumDemangle.h . Referenced by getArrayCache() , hasArray() , Node() , and ParameterPack::ParameterPack() . ◆  FunctionCache Cache Node::FunctionCache protected Track if this node is a (possibly qualified) function type. This can affect how we format the output string. Definition at line 218 of file ItaniumDemangle.h . Referenced by getFunctionCache() , hasFunction() , Node() , and ParameterPack::ParameterPack() . ◆  RHSComponentCache Cache Node::RHSComponentCache protected Tracks if this node has a component on its right side, in which case we need to call printRight. Definition at line 210 of file ItaniumDemangle.h . Referenced by getRHSComponentCache() , hasRHSComponent() , Node() , ParameterPack::ParameterPack() , and print() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Resizing,-rotating,-cropping-and-converting | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/dir_97cdd6ae7e6843add574fb55e792badd.html | LLVM: include/llvm/Analysis Directory Reference LLVM  22.0.0git include llvm Analysis Analysis Directory Reference Directory dependency graph for Analysis: This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead. Directories   Utils Files   AliasAnalysis.h   AliasAnalysisEvaluator.h   This file implements a simple N^2 alias analysis accuracy evaluator.   AliasSetTracker.h   AssumeBundleQueries.h   AssumptionCache.h   BasicAliasAnalysis.h   This is the interface for LLVM's primary stateless and local alias analysis.   BlockFrequencyInfo.h   BlockFrequencyInfoImpl.h   BranchProbabilityInfo.h   CallGraph.h   This file provides interfaces used to build and manipulate a call graph, which is a very useful tool for interprocedural optimization.   CallGraphSCCPass.h   CallPrinter.h   CaptureTracking.h   CFG.h   CFGPrinter.h   CFGSCCPrinter.h   CGSCCPassManager.h   This header provides classes for managing passes over SCCs of the call graph.   CmpInstAnalysis.h   CodeMetrics.h   ConstantFolding.h   ConstraintSystem.h   CostModel.h   CtxProfAnalysis.h   CycleAnalysis.h   This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycleInfo.   DDG.h   DDGPrinter.h   Delinearization.h   DemandedBits.h   DependenceAnalysis.h   DependenceGraphBuilder.h   DomConditionCache.h   DominanceFrontier.h   DominanceFrontierImpl.h   DomPrinter.h   DomTreeUpdater.h   DOTGraphTraitsPass.h   DXILMetadataAnalysis.h   DXILResource.h   EHUtils.h   EphemeralValuesCache.h   FloatingPointPredicateUtils.h   FunctionPropertiesAnalysis.h   GenericDomTreeUpdater.h   GenericDomTreeUpdaterImpl.h   GlobalsModRef.h   This is the interface for a simple mod/ref and alias analysis over globals.   GuardUtils.h   HashRecognize.h   HeatUtils.h   IndirectCallPromotionAnalysis.h   Interface to identify indirect call promotion candidates.   IndirectCallVisitor.h   InlineAdvisor.h   InlineCost.h   InlineModelFeatureMaps.h   InlineOrder.h   InstCount.h   InstructionPrecedenceTracking.h   InstructionSimplify.h   InstSimplifyFolder.h   InteractiveModelRunner.h   InterestingMemoryOperand.h   IR2Vec.h   This file defines the IR2Vec vocabulary analysis(IR2VecVocabAnalysis) , the core ir2vec::Embedder interface for generating IR embeddings, and related utilities like the IR2VecPrinterPass.   IRSimilarityIdentifier.h   IteratedDominanceFrontier.h   IVDescriptors.h   IVUsers.h   KernelInfo.h   LastRunTrackingAnalysis.h   LazyBlockFrequencyInfo.h   LazyBranchProbabilityInfo.h   LazyCallGraph.h   Implements a lazy call graph analysis and related passes for the new pass manager.   LazyValueInfo.h   Lint.h   Loads.h   LoopAccessAnalysis.h   LoopAnalysisManager.h   This header provides classes for managing per-loop analyses.   LoopCacheAnalysis.h   This file defines the interface for the loop cache analysis.   LoopInfo.h   LoopIterator.h   LoopNestAnalysis.h   This file defines the interface for the loop nest analysis.   LoopPass.h   LoopUnrollAnalyzer.h   MemDerefPrinter.h   MemoryBuiltins.h   MemoryDependenceAnalysis.h   MemoryLocation.h   This file provides utility analysis objects describing memory locations.   MemoryProfileInfo.h   MemorySSA.h   This file exposes an interface to building/using memory SSA to walk memory instructions using a use/def graph.   MemorySSAUpdater.h   MLInlineAdvisor.h   MLModelRunner.h   ModelUnderTrainingRunner.h   ModuleDebugInfoPrinter.h   ModuleSummaryAnalysis.h   This is the interface to build a ModuleSummaryIndex for a module.   MustExecute.h   Contains a collection of routines for determining if a given instruction is guaranteed to execute if a given point in control flow is reached.   NoInferenceModelRunner.h   ObjCARCAliasAnalysis.h   This file declares a simple ARC-aware AliasAnalysis using special knowledge of Objective C to enhance other optimization passes which rely on the Alias Analysis infrastructure.   ObjCARCAnalysisUtils.h   This file defines common analysis utilities used by the ObjC ARC Optimizer.   ObjCARCInstKind.h   ObjCARCUtil.h   This file defines ARC utility functions which are used by various parts of the compiler.   OptimizationRemarkEmitter.h   OverflowInstAnalysis.h   Passes.h   PHITransAddr.h   PhiValues.h   PostDominators.h   ProfileSummaryInfo.h   PtrUseVisitor.h   This file provides a collection of visitors which walk the (instruction) uses of a pointer.   RegionInfo.h   RegionInfoImpl.h   RegionIterator.h   RegionPass.h   RegionPrinter.h   ReleaseModeModelRunner.h   ReplayInlineAdvisor.h   RuntimeLibcallInfo.h   ScalarEvolution.h   ScalarEvolutionAliasAnalysis.h   This is the interface for a SCEV-based alias analysis.   ScalarEvolutionDivision.h   ScalarEvolutionExpressions.h   ScalarEvolutionNormalization.h   ScalarEvolutionPatternMatch.h   ScopedNoAliasAA.h   This is the interface for a metadata-based scoped no-alias analysis.   SimplifyQuery.h   SparsePropagation.h   StackLifetime.h   StackSafetyAnalysis.h   StaticDataProfileInfo.h   StructuralHash.h   SyntheticCountsUtils.h   TargetFolder.h   TargetLibraryInfo.h   TargetTransformInfo.h   This pass exposes codegen information to IR-level passes.   TargetTransformInfoImpl.h   This file provides helpers for the implementation of a TargetTransformInfo-conforming class.   TensorSpec.h   Trace.h   TypeBasedAliasAnalysis.h   This is the interface for a metadata-based TBAA.   TypeMetadataUtils.h   UniformityAnalysis.h   LLVM IR instance of the generic uniformity analysis.   ValueLattice.h   ValueLatticeUtils.h   ValueTracking.h   VectorUtils.h   WithCache.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Saving-to-a-file | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://www.php.net/manual/tr/function.tidy-warning-count.php | PHP: tidy_warning_count - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box Tokenizer » « tidy_get_output PHP Kılavuzu İşlev Başvuru Kılavuzu Diğer Temel Eklentiler Tidy Tidy İşlevleri Change language: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other tidy_warning_count (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) tidy_warning_count — Belgede saptanan Tidy uyarılarının sayısını döndürür Açıklama tidy_warning_count ( tidy $tidy ): int Belgede saptanan Tidy uyarılarının sayısını döndürür. Bağımsız Değişkenler tidy Tidy nesnesi. Dönen Değerler Uyarı sayısı. Örnekler Örnek 1 - tidy_warning_count() örneği <?php $html = '<p>test</i> <bogustag>bogus</bogustag>' ; $tidy = tidy_parse_string ( $html ); echo tidy_error_count ( $tidy ) . "\n" ; //1 echo tidy_warning_count ( $tidy ) . "\n" ; //5 ?> Ayrıca Bakınız tidy_error_count() - Belgede saptanan Tidy hatalarının sayısını döndürür tidy_access_count() - Belgede saptanan Tidy erişilebilirlik uyarılarının sayısını döndürür Found A Problem? Learn How To Improve This Page • Submit a Pull Request • Report a Bug + add a note User Contributed Notes There are no user contributed notes for this page. Tidy İşlevleri ob_​tidyhandler tidy_​access_​count tidy_​config_​count tidy_​error_​count tidy_​get_​output tidy_​warning_​count Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/namespacestd.html#ab8424022895aee3e366fb9a32f2883cb | LLVM: std Namespace Reference LLVM  22.0.0git Classes | Functions std Namespace Reference Implement std::hash so that hash_code can be used in STL containers. More... Classes struct   hash< llvm::hash_code > struct   hash< llvm::pdb::PDB_SymType > struct   hash< llvm::rdf::detail::NodeRef > struct   hash< llvm::rdf::RegisterAggr > struct   hash< llvm::rdf::RegisterRef > struct   hash< llvm::sampleprof::FunctionId >   Template specialization for FunctionId so that it can be used in STL containers. More... struct   hash< SDValue > struct   hash< VarLocInsertPt > struct   is_error_code_enum< llvm::BitcodeError > struct   is_error_code_enum< llvm::codeview::cv_error_code > struct   is_error_code_enum< llvm::errc > struct   is_error_code_enum< llvm::msf::msf_error_code > struct   is_error_code_enum< llvm::object::object_error > struct   is_error_code_enum< llvm::pdb::dia_error_code > struct   is_error_code_enum< llvm::pdb::pdb_error_code > struct   is_error_code_enum< llvm::pdb::raw_error_code > struct   is_error_code_enum< llvm::sampleprof_error > class   reverse_iterator< llvm::DWARFDie::iterator > struct   tuple_element< I, const llvm::detail::enumerator_result< Refs... > > struct   tuple_element< I, llvm::detail::enumerator_result< Refs... > > struct   tuple_element< I, llvm::PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > > struct   tuple_element< Index, llvm::StringMapEntry< ValueTy > > struct   tuple_size< llvm::detail::enumerator_result< Refs... > > struct   tuple_size< llvm::PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > > struct   tuple_size< llvm::StringMapEntry< ValueTy > > Functions void  swap ( llvm::BitVector & LHS , llvm::BitVector & RHS )   Implement std::swap in terms of BitVector swap. template<class Ty> void  swap ( llvm::iplist < Ty > &Left, llvm::iplist < Ty > &Right) template<typename T , typename V, typename S, unsigned N> void  swap ( llvm::SetVector < T , V, S, N > & LHS , llvm::SetVector < T , V, S, N > & RHS )   Implement std::swap in terms of SetVector swap. template<typename T , unsigned N> void  swap ( llvm::SmallSetVector < T , N > & LHS , llvm::SmallSetVector < T , N > & RHS )   Implement std::swap in terms of SmallSetVector swap. void  swap ( llvm::SmallBitVector & LHS , llvm::SmallBitVector & RHS )   Implement std::swap in terms of BitVector swap. template<class T , unsigned N> void  swap ( llvm::SmallPtrSet < T , N > & LHS , llvm::SmallPtrSet < T , N > & RHS )   Implement std::swap in terms of SmallPtrSet swap. template<typename T > void  swap ( llvm::SmallVectorImpl < T > & LHS , llvm::SmallVectorImpl < T > & RHS )   Implement std::swap in terms of SmallVector swap. template<typename T , unsigned N> void  swap ( llvm::SmallVector < T , N > & LHS , llvm::SmallVector < T , N > & RHS )   Implement std::swap in terms of SmallVector swap. Detailed Description Implement std::hash so that hash_code can be used in STL containers. Function Documentation ◆  swap() [1/8] void std::swap ( llvm::BitVector & LHS , llvm::BitVector & RHS  ) inline Implement std::swap in terms of BitVector swap. Definition at line 872 of file BitVector.h . References LHS , and RHS . Referenced by addAttributeImpl() , llvm::logicalview::LVRange::addEntry() , llvm::PressureDiff::addPressureChange() , adjustICmp128() , llvm::AMDGPUAAResult::alias() , llvm::coro::Shape::analyze() , analyzeICmp() , llvm::CombinerHelper::applyCombineAddP2IToPtrAdd() , llvm::SPIRVCombinerHelper::applySPIRVFaceForward() , llvm::MemoryDepChecker::areDepsSafe() , attemptToFoldSymbolOffsetDifference() , llvm::SUnit::biasCriticalPath() , llvm::SparcTargetLowering::bitcastConstantFPToInt() , llvm::memprof::CallStackRadixTreeBuilder< FrameIdTy >::build() , llvm::TargetLowering::buildLegalVectorShuffle() , canonicalHeaderAndLatch() , canonicalizeAbs() , llvm::SelectionDAG::canonicalizeCommutativeBinop() , llvm::InstCombinerImpl::canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract() , canonicalizeForInvariantConditionInjection() , canonicalizeICmpBool() , canonicalizeSaturatedAddSigned() , canonicalizeSaturatedAddUnsigned() , canonicalizeSaturatedSubtract() , canonicalizeShuffleMaskWithHorizOp() , checkBiasedBranch() , checkForNegativeOperand() , llvm::MachineBasicBlock::clearLiveIns() , combineADDToADDZE() , combineADDToMAT_PCREL_ADDR() , combineANDOfSETCCToCZERO() , combineAndOrForCcmpCtest() , combineBinOpOfExtractToReduceTree() , combineCarryDiamond() , combineCMov() , combineFMulcFCMulc() , combineFunnelShift() , combineHorizOpWithShuffle() , combineLogicBlendIntoConditionalNegate() , combineMul() , combineOp_VLToVWOp_VL() , combineOrCmpEqZeroToCtlzSrl() , combinePExtTruncate() , combineSelect() , llvm::VETargetLowering::combineSelect() , combineSelectAndUse() , combineSelectAndUse() , combineSelectAndUse() , llvm::VETargetLowering::combineSelectCC() , combineSelectOfTwoConstants() , combineSetCC() , combineShuffleToFMAddSub() , combineSVEPrefetchVecBaseImmOff() , combineTargetShuffle() , combineToVWMACC() , combineVqdotAccum() , combineVSelectWithAllOnesOrZeros() , combineX86ShuffleChainWithExtract() , combineX86ShufflesRecursively() , llvm::SIInstrInfo::commuteInstructionImpl() , commuteShuffle() , llvm::KnownBits::computeForAddSub() , llvm::KnownBits::computeForSubBorrow() , llvm::SelectionDAG::computeKnownBits() , llvm::AArch64TargetLowering::computeKnownBitsForTargetNode() , llvm::ARMTargetLowering::computeKnownBitsForTargetNode() , computeMergedBranchWeights() , llvm::SelectionDAG::ComputeNumSignBits() , constantFoldBinOpWithSplat() , llvm::ConstantFoldTerminator() , llvm::InstCombinerImpl::convertOrOfShiftsToFunnelShift() , llvm::SelectionDAG::copyExtraInfo() , countToEliminateCompares() , createGPRPairNode() , createGPRPairNodei64() , createPHIsForCMOVsInSinkBB() , createPHIsForSelects() , llvm::DomTreeBuilder::DeleteEdge() , detectExtMul() , detectPMADDUBSW() , detectShiftUntilBitTestIdiom() , detectShiftUntilZeroIdiom() , llvm::SIRegisterInfo::eliminateFrameIndex() , llvm::orc::detail::WaitingOnGraph< JITDylib *, NonOwningSymbolStringPtr >::emit() , emitBuildPairF64Pseudo() , EmitCMP() , emitConjunctionRec() , llvm::ARMTargetLowering::EmitInstrWithCustomInserter() , llvm::ARMTargetLowering::emitLoadLinked() , llvm::MipsSEFrameLowering::emitPrologue() , emitSplitF64Pseudo() , llvm::ARMTargetLowering::emitStoreConditional() , llvm::DominatorTreeBase< BlockT, false >::eraseNode() , estimateLoopTripCount() , llvm::MCExpr::evaluateAsRelocatableImpl() , llvm::TargetLowering::expandCMP() , expandSGPRCopy() , llvm::gsym::GsymCreator::finalize() , llvm::orc::EPCGenericJITLinkMemoryManager::InFlightAlloc::finalize() , llvm::orc::MapperJITLinkMemoryManager::InFlightAlloc::finalize() , llvm::orc::EPCGenericRTDyldMemoryManager::finalizeMemory() , llvm::TargetRegisterInfo::findCommonRegClass() , llvm::DominatorTreeBase< BlockT, false >::findNearestCommonDominator() , llvm::CoalescerPair::flip() , foldAbsDiff() , foldAndOrOfICmpsWithPow2AndWithZero() , foldBinOpIntoSelectIfProfitable() , foldBinOpIntoSelectIfProfitable() , foldCSELOfCSEL() , foldFCmpFNegCommonOp() , foldFCmpWithFloorAndCeil() , llvm::AMDGPUTargetLowering::foldFreeOpFromSelect() , foldGuardedFunnelShift() , foldICmpAndXX() , foldICmpOrXX() , llvm::InstCombinerImpl::foldICmpTruncWithTruncOrExt() , foldICmpWithLowBitMaskedVal() , llvm::InstCombinerImpl::foldICmpWithMinMax() , foldICmpXorXX() , foldIntrinsicUsingDistributiveLaws() , foldIsPowerOf2() , foldLoadsRecursive() , foldMulHigh() , foldMulShl1() , foldOrCommuteConstant() , foldReduceOperandViaVQDOT() , foldSelectICmpAndZeroShl() , foldSelectICmpLshrAshr() , foldSelectICmpMinMax() , foldSelectShuffleOfSelectShuffle() , foldSelectWithIdentityConstant() , foldSelectZeroOrFixedOp() , foldShiftIntoShiftInAnotherHandOfAndInICmp() , foldShuffleWithInsert() , foldTwoEntryPHINode() , foldUnsignedUnderflowCheck() , llvm::InstCombinerImpl::foldVectorBinop() , foldVSelectToSignBitSplatMask() , generateEquivalentSub() , GenerateTBL() , getAArch64Cmp() , getBranchHint() , llvm::getBranchProbability() , getBranchWeights() , getBuildVectorSplat() , getCmp() , llvm::TargetRegisterInfo::getCommonSuperRegClass() , getCopyFromParts() , llvm::PPCMCCodeEmitter::getDispRI34PCRelEncoding() , getDivRemArgList() , getHashValueImpl() , getI128Select() , llvm::GetIfCondition() , llvm::Loop::getIncomingAndBackEdge() , llvm::getLoopEstimatedTripCount() , llvm::ScalarEvolution::getLoopInvariantExitCondDuringFirstIterationsImpl() , llvm::ScalarEvolution::getLoopInvariantPredicate() , llvm::getMetadataToPropagate() , llvm::SelectionDAG::getNode() , llvm::AMDGPUSubtarget::getOccupancyWithWorkGroupSizes() , getOperandsForBranch() , llvm::PeelingModuloScheduleExpander::getPhiCanonicalReg() , llvm::ARMTargetLowering::getPostIndexedAddressParts() , llvm::PPCTargetLowering::getPreIndexedAddressParts() , llvm::TargetInstrInfo::getReassociationOpcodes() , llvm::RegBankSelect::getRepairCost() , getShuffleHalfVectors() , llvm::getShuffleMaskWithWidestElts() , llvm::getStartAndEndForAccess() , getTestBitReg() , getThreeSrcCommuteCase() , getZeroPaddedAdd() , GroupByComplexity() , llvm::orc::SimpleRemoteEPC::handleDisconnect() , llvm::orc::SimpleRemoteEPCServer::handleDisconnect() , llvm::VPlanTransforms::handleMultiUseReductions() , handlePhiDef() , llvm::TargetInstrInfo::hasReassociableSibling() , hoistAdd() , hoistAddSub() , hoistBOAssociation() , hoistMinMax() , hoistMulAddAssociation() , hoistSub() , llvm::GCNRegPressure::inc() , llvm::orc::SimpleRemoteMemoryMapper::initialize() , llvm::InlineFunctionImpl() , llvm::DomTreeBuilder::InsertEdge() , insertFoldCacheEntry() , insertNoDuplicates() , llvm::SIInstrInfo::insertSelect() , llvm::GCNTTIImpl::instCombineIntrinsic() , interChangeDependencies() , isAddSubOrSubAdd() , llvm::CoalescerPair::isCoalescable() , isFNEG() , isHorizontalBinOp() , isI128MovedFromParts() , isImpliedCondFCmps() , isImpliedCondICmps() , isKnownPredicateExtendIdiom() , IsKnownPredicateViaMinOrMax() , isLegalToInterChangeLoops() , isLoopNeverExecuted() , isMaskedSlidePair() , isSetCC() , isSignedMinMaxClamp() , isSignedMinMaxIntrinsicClamp() , legalizeFCmpPredicate() , llvm::AMDGPULegalizerInfo::legalizeIntrinsic() , llvm::TargetLowering::LegalizeSetCCCondCode() , llvm::cfg::LegalizeUpdates() , LLVMOrcCreateRTDyldObjectLinkingLayerWithMCJITMemoryManagerLikeCallbacks() , lowerAddSubToHorizontalOp() , LowerAndToBT() , LowerAndToBTST() , llvm::RISCVTargetLowering::LowerCall() , LowerFMINIMUM_FMAXIMUM() , llvm::SparcTargetLowering::LowerFormalArguments_32() , LowerIntVSETCC_AVX512() , lowerMSABinaryBitImmIntr() , lowerMSASplatZExt() , LowerMUL() , llvm::RISCVTargetLowering::LowerOperation() , llvm::RISCVTargetLowering::LowerReturn() , LowerShift() , lowerShuffleAsBlend() , lowerShuffleAsLanePermuteAndRepeatedMask() , lowerShuffleWithPERMV() , lowerShuffleWithSHUFPS() , llvm::LegalizerHelper::lowerThreewayCompare() , lowerV8I16GeneralSingleInputShuffle() , llvm::HexagonTargetLowering::LowerVECTOR_SHUFFLE() , LowerVECTOR_SHUFFLE() , lowerVECTOR_SHUFFLE() , lowerVECTOR_SHUFFLEAsVSlide1() , LowerVSETCC() , LowerVSETCC() , LowerVSETCCWithSUBUS() , matchBinaryShuffle() , matchBitmaskMul() , llvm::CombinerHelper::matchCanonicalizeFCmp() , llvm::CombinerHelper::matchCanonicalizeICmp() , matchClamp() , llvm::CombinerHelper::matchCombineFAddFMAFMulToFMadOrFMA() , llvm::CombinerHelper::matchCombineFAddFMulToFMadOrFMA() , llvm::CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMA() , llvm::CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMAAggressive() , matchCondition() , matchFastFloatClamp() , matchMinMaxOfMinMax() , matchOrConcat() , matchPMADDWD() , matchPMADDWD_2() , llvm::CombinerHelper::matchRepeatedFPDivisor() , matchSelectAddSub() , llvm::CombinerHelper::matchSelectIMinMax() , matchSelectPattern() , llvm::SPIRVCombinerHelper::matchSelectToFaceForward() , matchSelectWithOptionalNotCond() , matchShuffleWithSHUFPD() , matchShuffleWithUNPCK() , llvm::InstCombinerImpl::matchThreeWayIntCompare() , llvm::CombinerHelper::matchXorOfAndWithSameReg() , mayUseP9Setb() , mergeConditionalStores() , mergeConditionalStoreToAddress() , MergeSeqs() , llvm::AliasSet::mergeSetIn() , llvm::LiveRange::MergeValueNumberInto() , llvm::hashing::detail::hash_state::mix() , llvm::LoopCarriedEdges::modifySUnits() , llvm::orc::SymbolStringPoolEntryUnsafe::moveToSymbolStringPtr() , multikeySort() , needsLFTR() , NegateCC() , llvm::FullDependence::normalize() , llvm::Triple::normalize() , llvm::AA::PointerInfo::State::operator=() , llvm::ItaniumPartialDemangler::operator=() , llvm::jitlink::JITLinkMemoryManager::FinalizedAlloc::operator=() , llvm::MustBeExecutedIterator::operator=() , llvm::orc::shared::WrapperFunctionBuffer::operator=() , llvm::orc::SymbolStringPtr::operator=() , llvm::Regex::operator=() , llvm::StringMap< EmptyStringSetTag, AllocatorTy >::operator=() , PODSmallVector< Node *, 8 >::operator=() , llvm::X86::optimizeInstFromVEX3ToVEX2() , llvm::LiveRange::overlaps() , llvm::LiveRange::overlapsFrom() , parseBraceExpansions() , AbstractManglingParser< Derived, Alloc >::parseFoldExpr() , llvm::LoopStructure::parseLoopStructure() , llvm::peelLoop() , llvm::PeelSingleBlockLoop() , performADDCombine() , performAddCSelIntoCSinc() , performAddDotCombine() , performAddTruncShiftCombine() , performANDORCSELCombine() , performBRCONDCombine() , llvm::ARMTargetLowering::PerformCMOVToBFICombine() , llvm::HexagonTargetLowering::PerformDAGCombine() , llvm::PPCTargetLowering::PerformDAGCombine() , llvm::RISCVTargetLowering::PerformDAGCombine() , performExtBinopLoadFold() , PerformFAddVSelectCombine() , performGatherLoadCombine() , PerformMinMaxCombine() , PerformMinMaxToSatCombine() , performMULCombine() , performMulCombine() , performORCombine() , performScatterStoreCombine() , performSELECT_CCCombine() , PerformSELECTCombine() , performSetccAddFolding() , performVecReduceAddCombine() , PerformVMOVRRDCombine() , PerformVMULCombine() , performVP_TRUNCATECombine() , PerformVSetCCToVCTPCombine() , llvm::LatencyPriorityQueue::pop() , llvm::ResourcePriorityQueue::pop() , llvm::gsym::GsymCreator::prepareMergedFunctions() , PrintResults() , slpvectorizer::BoUpSLP::processBuildVector() , pushAddIntoCmovOfConsts() , reassociateCSELOperandsForCSE() , reassociateFCmps() , llvm::TargetInstrInfo::reassociateOps() , reconnectChildLoops() , llvm::orc::shared::WrapperFunctionBuffer::release() , llvm::LatencyPriorityQueue::remove() , llvm::orc::SymbolLookupSet::remove() , llvm::ResourcePriorityQueue::remove() , llvm::DomTreeBuilder::SemiNCAInfo< DomTreeT >::RemoveRedundantRoots() , ReorganizeVector() , llvm::RegBankSelect::repairReg() , ReplaceATOMIC_LOAD_128Results() , ReplaceCMP_SWAP_128Results() , llvm::RISCVTargetLowering::ReplaceNodeResults() , llvm::SIRegisterInfo::resolveFrameIndex() , llvm::AArch64FrameLowering::restoreCalleeSavedRegisters() , llvm::ScalarEvolution::LoopGuards::rewrite() , runImpl() , llvm::mca::Scheduler::select() , selectUmullSmull() , llvm::setBranchProbability() , setLimitsForBinOp() , llvm::setLoopEstimatedTripCount() , llvm::CoalescerPair::setRegisters() , llvm::orc::rt_bootstrap::SimpleExecutorDylibManager::shutdown() , llvm::InstCombinerImpl::SimplifyAddWithRemainder() , llvm::simplifyBinaryIntrinsic() , simplifyCmpSelOfMaxMin() , simplifyFCmpInst() , simplifyFMAFMul() , simplifyICmpInst() , llvm::ScalarEvolution::SimplifyICmpOperands() , simplifyICmpWithBinOp() , simplifyICmpWithMinMax() , simplifyIntrinsic() , simplifyLoopInst() , simplifySelectWithFCmp() , simplifySelectWithICmpCond() , simplifyShuffleVectorInst() , simplifySuspendPoints() , simplifySwitchOfCmpIntrinsic() , llvm::AArch64FrameLowering::spillCalleeSavedRegisters() , llvm::CallGraphNode::stealCalledFunctionsFrom() , llvm::AllocatorList< T, BumpPtrAllocator >< Addend >::swap() , llvm::Any::swap() , llvm::BitVector::swap() , llvm::CachedHashString::swap , llvm::CGSCCToFunctionPassAdaptor::swap , llvm::detail::AnalysisPassModel< IRUnitT, PassT, InvalidatorT, ExtraArgTs >::swap , llvm::detail::AnalysisResultModel< IRUnitT, PassT, ResultT, InvalidatorT, false >::swap , llvm::detail::AnalysisResultModel< IRUnitT, PassT, ResultT, InvalidatorT, true >::swap , llvm::detail::PassModel< IRUnitT, PassT, AnalysisManagerT, ExtraArgTs >::swap , llvm::MapVector< StringRef, HashData >::swap() , llvm::ModuleToPostOrderCGSCCPassAdaptor::swap , llvm::simple_ilist< Node >::swap() , llvm::SmallBitVector::swap() , llvm::SmallPtrSetImplBase::swap() , llvm::SmallVectorImpl< T >::swap() , llvm::StringMapImpl::swap() , llvm::xray::Profile::swap , swap() , swap() , llvm::GVNExpression::BasicExpression::swapOperands() , llvm::VPUser::swapOperands() , llvm::VPBlockBase::swapPredecessors() , llvm::BranchProbabilityInfo::swapSuccEdgesProbabilities() , llvm::VPBlockBase::swapSuccessors() , llvm::SwingSchedulerDDGEdge::SwingSchedulerDDGEdge() , Swizzle() , llvm::orc::SymbolStringPtr::SymbolStringPtr() , llvm::orc::SymbolStringPoolEntryUnsafe::take() , llvm::AddrLabelMap::takeDeletedSymbolsForFunction() , threadCmpOverPHI() , threadCmpOverSelect() , TranslateM68kCC() , translateSetCCForBranch() , translateSetCCForBranch() , TranslateX86CC() , translateX86FSETCC() , tryBitfieldInsertOpFromOr() , tryDemorganOfBooleanCondition() , tryFactorization() , tryFoldMADwithSRL() , tryFoldSelectIntoOp() , TryMULWIDECombine() , llvm::tryPressure() , trySequenceOfOnes() , trySimplifyICmpWithAdds() , llvm::VPRecipeBuilder::tryToCreatePartialReduction() , unpackF64OnRV32DSoftABI() , llvm::MCJIT::UnregisterJITEventListener() , updateBranchWeights() , upgradeX86ConcatShift() , upgradeX86IntrinsicCall() , upgradeX86VPERMT2Intrinsics() , valuesOverlap() , shuffles::vdealvdd() , llvm::InstCombinerImpl::visitAdd() , llvm::InstCombinerImpl::visitCallInst() , llvm::InstCombinerImpl::visitICmpInst() , llvm::InstCombinerImpl::visitOr() , llvm::InstCombinerImpl::visitShl() , llvm::SelectionDAGBuilder::visitSwitchCase() , llvm::InstCombinerImpl::visitXor() , shuffles::vshuffvdd() , llvm::orc::shared::WrapperFunctionBuffer::WrapperFunctionBuffer() , llvm::reassociate::XorOpnd::XorOpnd() , and llvm::orc::DefinitionGenerator::~DefinitionGenerator() . ◆  swap() [2/8] template<class Ty> void std::swap ( llvm::iplist < Ty > & Left , llvm::iplist < Ty > & Right  ) Definition at line 352 of file ilist.h . ◆  swap() [3/8] template<typename T , typename V, typename S, unsigned N> void std::swap ( llvm::SetVector < T , V, S, N > & LHS , llvm::SetVector < T , V, S, N > & RHS  ) inline Implement std::swap in terms of SetVector swap. Definition at line 350 of file SetVector.h . References LHS , and RHS . ◆  swap() [4/8] void std::swap ( llvm::SmallBitVector & LHS , llvm::SmallBitVector & RHS  ) inline Implement std::swap in terms of BitVector swap. Definition at line 761 of file SmallBitVector.h . References LHS , and RHS . ◆  swap() [5/8] template<class T , unsigned N> void std::swap ( llvm::SmallPtrSet < T , N > & LHS , llvm::SmallPtrSet < T , N > & RHS  ) inline Implement std::swap in terms of SmallPtrSet swap. Definition at line 595 of file SmallPtrSet.h . References LHS , and RHS . ◆  swap() [6/8] template<typename T , unsigned N> void std::swap ( llvm::SmallSetVector < T , N > & LHS , llvm::SmallSetVector < T , N > & RHS  ) inline Implement std::swap in terms of SmallSetVector swap. Definition at line 358 of file SetVector.h . References LHS , and RHS . ◆  swap() [7/8] template<typename T , unsigned N> void std::swap ( llvm::SmallVector < T , N > & LHS , llvm::SmallVector < T , N > & RHS  ) inline Implement std::swap in terms of SmallVector swap. Definition at line 1364 of file SmallVector.h . References LHS , RHS , and swap() . ◆  swap() [8/8] template<typename T > void std::swap ( llvm::SmallVectorImpl < T > & LHS , llvm::SmallVectorImpl < T > & RHS  ) inline Implement std::swap in terms of SmallVector swap. Definition at line 1357 of file SmallVector.h . References LHS , RHS , and swap() . Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/DemangleConfig_8h.html#aacd584e2ac8072e41efbd2f3c2e439ca | LLVM: include/llvm/Demangle/DemangleConfig.h File Reference LLVM  22.0.0git include llvm Demangle Macros DemangleConfig.h File Reference #include "llvm/Config/llvm-config.h" #include <cassert> Go to the source code of this file. Macros #define  __has_feature (x) #define  __has_cpp_attribute (x) #define  __has_attribute (x) #define  __has_builtin (x) #define  DEMANGLE_GNUC_PREREQ (maj, min, patch) #define  DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_UNREACHABLE #define  DEMANGLE_ATTRIBUTE_NOINLINE #define  DEMANGLE_DUMP_METHOD     DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_FALLTHROUGH #define  DEMANGLE_ASSERT (__expr, __msg) #define  DEMANGLE_NAMESPACE_BEGIN    namespace llvm { namespace itanium_demangle { #define  DEMANGLE_NAMESPACE_END    } } #define  DEMANGLE_ABI   DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Macro Definition Documentation ◆  __has_attribute #define __has_attribute ( x ) Value: 0 Definition at line 30 of file DemangleConfig.h . ◆  __has_builtin #define __has_builtin ( x ) Value: 0 Definition at line 34 of file DemangleConfig.h . ◆  __has_cpp_attribute #define __has_cpp_attribute ( x ) Value: 0 Definition at line 26 of file DemangleConfig.h . ◆  __has_feature #define __has_feature ( x ) Value: 0 Definition at line 22 of file DemangleConfig.h . ◆  DEMANGLE_ABI #define DEMANGLE_ABI DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Definition at line 115 of file DemangleConfig.h . Referenced by llvm::ms_demangle::Node::output() , parse_discriminator() , and llvm::ms_demangle::Demangler::~Demangler() . ◆  DEMANGLE_ASSERT #define DEMANGLE_ASSERT ( __expr , __msg  ) Value: assert ((__expr) && (__msg)) assert assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!") Definition at line 94 of file DemangleConfig.h . Referenced by OutputBuffer::back() , PODSmallVector< Node *, 8 >::back() , ExplicitObjectParameter::ExplicitObjectParameter() , SpecialSubstitution::getBaseName() , AbstractManglingParser< Derived, Alloc >::OperatorInfo::getSymbol() , OutputBuffer::insert() , PODSmallVector< Node *, 8 >::operator[]() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnresolvedName() , PODSmallVector< Node *, 8 >::pop_back() , AbstractManglingParser< Derived, Alloc >::popTrailingNodeArray() , PODSmallVector< Node *, 8 >::shrinkToSize() , Node::visit() , and AbstractManglingParser< Derived, Alloc >::ScopedTemplateParamList::~ScopedTemplateParamList() . ◆  DEMANGLE_ATTRIBUTE_NOINLINE #define DEMANGLE_ATTRIBUTE_NOINLINE Definition at line 69 of file DemangleConfig.h . ◆  DEMANGLE_ATTRIBUTE_USED #define DEMANGLE_ATTRIBUTE_USED Definition at line 53 of file DemangleConfig.h . ◆  DEMANGLE_DUMP_METHOD #define DEMANGLE_DUMP_METHOD    DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED Definition at line 73 of file DemangleConfig.h . Referenced by Node::dump() . ◆  DEMANGLE_FALLTHROUGH #define DEMANGLE_FALLTHROUGH Definition at line 85 of file DemangleConfig.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseType() . ◆  DEMANGLE_GNUC_PREREQ #define DEMANGLE_GNUC_PREREQ ( maj , min , patch  ) Value: 0 Definition at line 46 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_BEGIN #define DEMANGLE_NAMESPACE_BEGIN   namespace llvm { namespace itanium_demangle { Definition at line 97 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_END #define DEMANGLE_NAMESPACE_END   } } Definition at line 98 of file DemangleConfig.h . ◆  DEMANGLE_UNREACHABLE #define DEMANGLE_UNREACHABLE Definition at line 61 of file DemangleConfig.h . Referenced by demanglePointerCVQualifiers() , ExpandedSpecialSubstitution::getBaseName() , and AbstractManglingParser< Derived, Alloc >::parseExpr() . Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNode.html#a17f6d6b0aa5b98942d8761935462eb5d | LLVM: Node Class Reference LLVM  22.0.0git Public Types | Public Member Functions | Protected Attributes | Friends | List of all members Node Class Reference abstract #include " llvm/Demangle/ItaniumDemangle.h " Inherited by FloatLiteralImpl< float > , FloatLiteralImpl< double > , FloatLiteralImpl< long double > , AbiTagAttr , ArraySubscriptExpr , ArrayType , BinaryExpr , BinaryFPType , BitIntType , BoolExpr , BracedExpr , BracedRangeExpr , CallExpr , CastExpr , ClosureTypeName , ConditionalExpr , ConstrainedTypeTemplateParamDecl , ConversionExpr , ConversionOperatorType , CtorDtorName , CtorVtableSpecialName , DeleteExpr , DotSuffix , DtorName , DynamicExceptionSpec , ElaboratedTypeSpefType , EnableIfAttr , EnclosingExpr , EnumLiteral , ExpandedSpecialSubstitution , ExplicitObjectParameter , ExprRequirement , FloatLiteralImpl< Float > , FoldExpr , ForwardTemplateReference , FunctionEncoding , FunctionParam , FunctionType , GlobalQualifiedName , InitListExpr , IntegerLiteral , LambdaExpr , LiteralOperator , LocalName , MemberExpr , MemberLikeFriendName , ModuleEntity , ModuleName , NameType , NameWithTemplateArgs , NestedName , NestedRequirement , NewExpr , NodeArrayNode , NoexceptSpec , NonTypeTemplateParamDecl , ObjCProtoName , ParameterPack , ParameterPackExpansion , PixelVectorType , PointerToMemberConversionExpr , PointerToMemberType , PointerType , PostfixExpr , PostfixQualifiedType , PrefixExpr , QualType , QualifiedName , ReferenceType , RequiresExpr , SizeofParamPackExpr , SpecialName , StringLiteral , StructuredBindingName , SubobjectExpr , SyntheticTemplateParamName , TemplateArgs , TemplateArgumentPack , TemplateParamPackDecl , TemplateParamQualifiedArg , TemplateTemplateParamDecl , ThrowExpr , TransformedType , TypeRequirement , TypeTemplateParamDecl , UnnamedTypeName , VectorType , and VendorExtQualType . Public Types enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Public Member Functions   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Protected Attributes Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Friends class  OutputBuffer Detailed Description Definition at line 166 of file ItaniumDemangle.h . Member Enumeration Documentation ◆  Cache enum class Node::Cache : uint8_t strong Three-way bool to track a cached value. Unknown is possible if this node has an unexpanded parameter pack below it that may affect this cache. Enumerator Yes  No  Unknown  Definition at line 175 of file ItaniumDemangle.h . ◆  Kind enum Node::Kind : uint8_t Definition at line 168 of file ItaniumDemangle.h . ◆  Prec enum class Node::Prec : uint8_t strong Operator precedence for expression nodes. Used to determine required parens in expression emission. Enumerator Primary  Postfix  Unary  Cast  PtrMem  Multiplicative  Additive  Shift  Spaceship  Relational  Equality  And  Xor  Ior  AndIf  OrIf  Conditional  Assign  Comma  Default  Definition at line 179 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  Node() [1/2] Node::Node ( Kind K_ , Prec Precedence_ = Prec::Primary , Cache RHSComponentCache_ = Cache::No , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 221 of file ItaniumDemangle.h . References ArrayCache , FunctionCache , No , Primary , and RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , ArraySubscriptExpr::ArraySubscriptExpr() , ArrayType::ArrayType() , BinaryExpr::BinaryExpr() , BinaryFPType::BinaryFPType() , BitIntType::BitIntType() , BoolExpr::BoolExpr() , BracedExpr::BracedExpr() , BracedRangeExpr::BracedRangeExpr() , CallExpr::CallExpr() , CastExpr::CastExpr() , ClosureTypeName::ClosureTypeName() , ConditionalExpr::ConditionalExpr() , ConstrainedTypeTemplateParamDecl::ConstrainedTypeTemplateParamDecl() , ConversionExpr::ConversionExpr() , ConversionOperatorType::ConversionOperatorType() , CtorDtorName::CtorDtorName() , CtorVtableSpecialName::CtorVtableSpecialName() , DeleteExpr::DeleteExpr() , DotSuffix::DotSuffix() , DtorName::DtorName() , DynamicExceptionSpec::DynamicExceptionSpec() , ElaboratedTypeSpefType::ElaboratedTypeSpefType() , EnableIfAttr::EnableIfAttr() , EnclosingExpr::EnclosingExpr() , EnumLiteral::EnumLiteral() , ExpandedSpecialSubstitution::ExpandedSpecialSubstitution() , ExplicitObjectParameter::ExplicitObjectParameter() , ExprRequirement::ExprRequirement() , FloatLiteralImpl< float >::FloatLiteralImpl() , FoldExpr::FoldExpr() , ForwardTemplateReference::ForwardTemplateReference() , FunctionEncoding::FunctionEncoding() , FunctionParam::FunctionParam() , FunctionType::FunctionType() , TemplateParamQualifiedArg::getArg() , FunctionEncoding::getAttrs() , VectorType::getBaseType() , ParameterPackExpansion::getChild() , QualType::getChild() , VectorType::getDimension() , FunctionEncoding::getName() , PointerType::getPointee() , FunctionEncoding::getRequires() , FunctionEncoding::getReturnType() , ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , VendorExtQualType::getTA() , VendorExtQualType::getTy() , GlobalQualifiedName::GlobalQualifiedName() , InitListExpr::InitListExpr() , IntegerLiteral::IntegerLiteral() , LambdaExpr::LambdaExpr() , LiteralOperator::LiteralOperator() , LocalName::LocalName() , MemberExpr::MemberExpr() , MemberLikeFriendName::MemberLikeFriendName() , ModuleEntity::ModuleEntity() , ModuleName::ModuleName() , NameType::NameType() , NameWithTemplateArgs::NameWithTemplateArgs() , NestedName::NestedName() , NestedRequirement::NestedRequirement() , NewExpr::NewExpr() , Node() , NodeArrayNode::NodeArrayNode() , NoexceptSpec::NoexceptSpec() , NonTypeTemplateParamDecl::NonTypeTemplateParamDecl() , ObjCProtoName::ObjCProtoName() , ParameterPack::ParameterPack() , ParameterPackExpansion::ParameterPackExpansion() , PixelVectorType::PixelVectorType() , PointerToMemberConversionExpr::PointerToMemberConversionExpr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , PostfixExpr::PostfixExpr() , PostfixQualifiedType::PostfixQualifiedType() , PrefixExpr::PrefixExpr() , RequiresExpr::printLeft() , QualifiedName::QualifiedName() , QualType::QualType() , ReferenceType::ReferenceType() , RequiresExpr::RequiresExpr() , SizeofParamPackExpr::SizeofParamPackExpr() , SpecialName::SpecialName() , StringLiteral::StringLiteral() , StructuredBindingName::StructuredBindingName() , SubobjectExpr::SubobjectExpr() , SyntheticTemplateParamName::SyntheticTemplateParamName() , TemplateArgs::TemplateArgs() , TemplateArgumentPack::TemplateArgumentPack() , TemplateParamPackDecl::TemplateParamPackDecl() , TemplateParamQualifiedArg::TemplateParamQualifiedArg() , TemplateTemplateParamDecl::TemplateTemplateParamDecl() , ThrowExpr::ThrowExpr() , TransformedType::TransformedType() , TypeRequirement::TypeRequirement() , TypeTemplateParamDecl::TypeTemplateParamDecl() , UnnamedTypeName::UnnamedTypeName() , VectorType::VectorType() , and VendorExtQualType::VendorExtQualType() . ◆  Node() [2/2] Node::Node ( Kind K_ , Cache RHSComponentCache_ , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 226 of file ItaniumDemangle.h . References No , Node() , and Primary . ◆  ~Node() virtual Node::~Node ( ) virtual default Member Function Documentation ◆  dump() DEMANGLE_DUMP_METHOD void Node::dump ( ) const References DEMANGLE_DUMP_METHOD . Referenced by llvm::DAGTypeLegalizer::run() , and llvm::RISCVDAGToDAGISel::Select() . ◆  getArrayCache() Cache Node::getArrayCache ( ) const inline Definition at line 262 of file ItaniumDemangle.h . References ArrayCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getBaseName() virtual std::string_view Node::getBaseName ( ) const inline virtual Reimplemented in AbiTagAttr , ExpandedSpecialSubstitution , GlobalQualifiedName , MemberLikeFriendName , ModuleEntity , NameType , NameWithTemplateArgs , NestedName , QualifiedName , and SpecialSubstitution . Definition at line 299 of file ItaniumDemangle.h . ◆  getFunctionCache() Cache Node::getFunctionCache ( ) const inline Definition at line 263 of file ItaniumDemangle.h . References FunctionCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getKind() Kind Node::getKind ( ) const inline Definition at line 258 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseCtorDtorName() , AbstractManglingParser< Derived, Alloc >::parseNestedName() , AbstractManglingParser< Derived, Alloc >::parseTemplateArgs() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnscopedName() , NodeArray::printAsString() , and llvm::msgpack::Document::writeToBlob() . ◆  getPrecedence() Prec Node::getPrecedence ( ) const inline Definition at line 260 of file ItaniumDemangle.h . Referenced by ArraySubscriptExpr::match() , BinaryExpr::match() , CallExpr::match() , CastExpr::match() , ConditionalExpr::match() , ConversionExpr::match() , DeleteExpr::match() , EnclosingExpr::match() , MemberExpr::match() , NewExpr::match() , PointerToMemberConversionExpr::match() , PostfixExpr::match() , PrefixExpr::match() , printAsOperand() , ArraySubscriptExpr::printLeft() , BinaryExpr::printLeft() , ConditionalExpr::printLeft() , MemberExpr::printLeft() , PostfixExpr::printLeft() , and PrefixExpr::printLeft() . ◆  getRHSComponentCache() Cache Node::getRHSComponentCache ( ) const inline Definition at line 261 of file ItaniumDemangle.h . References RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , QualType::QualType() , and ReferenceType::ReferenceType() . ◆  getSyntaxNode() virtual const Node * Node::getSyntaxNode ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , and ParameterPack . Definition at line 271 of file ItaniumDemangle.h . References Node() , and OutputBuffer . ◆  hasArray() bool Node::hasArray ( OutputBuffer & OB ) const inline Definition at line 246 of file ItaniumDemangle.h . References ArrayCache , hasArraySlow() , OutputBuffer , Unknown , and Yes . ◆  hasArraySlow() virtual bool Node::hasArraySlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , ParameterPack , and QualType . Definition at line 266 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasArray() . ◆  hasFunction() bool Node::hasFunction ( OutputBuffer & OB ) const inline Definition at line 252 of file ItaniumDemangle.h . References FunctionCache , hasFunctionSlow() , OutputBuffer , Unknown , and Yes . ◆  hasFunctionSlow() virtual bool Node::hasFunctionSlow ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , and QualType . Definition at line 267 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasFunction() . ◆  hasRHSComponent() bool Node::hasRHSComponent ( OutputBuffer & OB ) const inline Definition at line 240 of file ItaniumDemangle.h . References hasRHSComponentSlow() , OutputBuffer , RHSComponentCache , Unknown , and Yes . ◆  hasRHSComponentSlow() virtual bool Node::hasRHSComponentSlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , PointerToMemberType , PointerType , QualType , and ReferenceType . Definition at line 265 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasRHSComponent() . ◆  print() void Node::print ( OutputBuffer & OB ) const inline Definition at line 286 of file ItaniumDemangle.h . References No , OutputBuffer , and RHSComponentCache . Referenced by llvm::ItaniumPartialDemangler::getFunctionDeclContextName() , llvm::DOTGraphTraits< AADepGraph * >::getNodeLabel() , llvm::DOTGraphTraits< const MachineFunction * >::getNodeLabel() , llvm::itaniumDemangle() , printAsOperand() , FoldExpr::printLeft() , and printNode() . ◆  printAsOperand() void Node::printAsOperand ( OutputBuffer & OB , Prec P = Prec::Default , bool StrictlyWorse = false  ) const inline Definition at line 275 of file ItaniumDemangle.h . References Default , getPrecedence() , OutputBuffer , P , and print() . Referenced by llvm::DOTGraphTraits< DOTFuncInfo * >::getBBName() , getSimpleNodeName() , llvm::operator<<() , llvm::VPIRMetadata::print() , and llvm::SimpleNodeLabelString() . ◆  printInitListAsType() virtual bool Node::printInitListAsType ( OutputBuffer & , const NodeArray &  ) const inline virtual Reimplemented in ArrayType . Definition at line 295 of file ItaniumDemangle.h . References OutputBuffer . ◆  visit() template<typename Fn> void Node::visit ( Fn F ) const Visit the most-derived object corresponding to this object. Visit the node. Calls F(P) , where P is the node cast to the appropriate derived class. Definition at line 2639 of file ItaniumDemangle.h . References DEMANGLE_ASSERT , and F . Friends And Related Symbol Documentation ◆  OutputBuffer friend class OutputBuffer friend Definition at line 309 of file ItaniumDemangle.h . References OutputBuffer . Referenced by ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , hasArray() , ArrayType::hasArraySlow() , ForwardTemplateReference::hasArraySlow() , hasArraySlow() , ParameterPack::hasArraySlow() , QualType::hasArraySlow() , hasFunction() , ForwardTemplateReference::hasFunctionSlow() , FunctionEncoding::hasFunctionSlow() , FunctionType::hasFunctionSlow() , hasFunctionSlow() , ParameterPack::hasFunctionSlow() , QualType::hasFunctionSlow() , hasRHSComponent() , ArrayType::hasRHSComponentSlow() , ForwardTemplateReference::hasRHSComponentSlow() , FunctionEncoding::hasRHSComponentSlow() , FunctionType::hasRHSComponentSlow() , hasRHSComponentSlow() , ParameterPack::hasRHSComponentSlow() , PointerToMemberType::hasRHSComponentSlow() , PointerType::hasRHSComponentSlow() , QualType::hasRHSComponentSlow() , ReferenceType::hasRHSComponentSlow() , OutputBuffer , print() , printAsOperand() , ClosureTypeName::printDeclarator() , ArrayType::printInitListAsType() , printInitListAsType() , AbiTagAttr::printLeft() , ArraySubscriptExpr::printLeft() , ArrayType::printLeft() , BinaryExpr::printLeft() , BinaryFPType::printLeft() , BitIntType::printLeft() , BoolExpr::printLeft() , BracedExpr::printLeft() , BracedRangeExpr::printLeft() , CallExpr::printLeft() , CastExpr::printLeft() , ClosureTypeName::printLeft() , ConditionalExpr::printLeft() , ConstrainedTypeTemplateParamDecl::printLeft() , ConversionExpr::printLeft() , ConversionOperatorType::printLeft() , CtorDtorName::printLeft() , CtorVtableSpecialName::printLeft() , DeleteExpr::printLeft() , DotSuffix::printLeft() , DtorName::printLeft() , DynamicExceptionSpec::printLeft() , ElaboratedTypeSpefType::printLeft() , EnableIfAttr::printLeft() , EnclosingExpr::printLeft() , EnumLiteral::printLeft() , ExplicitObjectParameter::printLeft() , ExprRequirement::printLeft() , FloatLiteralImpl< float >::printLeft() , FoldExpr::printLeft() , ForwardTemplateReference::printLeft() , FunctionEncoding::printLeft() , FunctionParam::printLeft() , FunctionType::printLeft() , GlobalQualifiedName::printLeft() , InitListExpr::printLeft() , IntegerLiteral::printLeft() , LambdaExpr::printLeft() , LiteralOperator::printLeft() , LocalName::printLeft() , MemberExpr::printLeft() , MemberLikeFriendName::printLeft() , ModuleEntity::printLeft() , ModuleName::printLeft() , NameType::printLeft() , NameWithTemplateArgs::printLeft() , NestedName::printLeft() , NestedRequirement::printLeft() , NewExpr::printLeft() , NodeArrayNode::printLeft() , NoexceptSpec::printLeft() , NonTypeTemplateParamDecl::printLeft() , ObjCProtoName::printLeft() , ParameterPack::printLeft() , ParameterPackExpansion::printLeft() , PixelVectorType::printLeft() , PointerToMemberConversionExpr::printLeft() , PointerToMemberType::printLeft() , PointerType::printLeft() , PostfixExpr::printLeft() , PostfixQualifiedType::printLeft() , PrefixExpr::printLeft() , QualifiedName::printLeft() , QualType::printLeft() , ReferenceType::printLeft() , RequiresExpr::printLeft() , SizeofParamPackExpr::printLeft() , SpecialName::printLeft() , SpecialSubstitution::printLeft() , StringLiteral::printLeft() , StructuredBindingName::printLeft() , SubobjectExpr::printLeft() , SyntheticTemplateParamName::printLeft() , TemplateArgs::printLeft() , TemplateArgumentPack::printLeft() , TemplateParamPackDecl::printLeft() , TemplateParamQualifiedArg::printLeft() , TemplateTemplateParamDecl::printLeft() , ThrowExpr::printLeft() , TransformedType::printLeft() , TypeRequirement::printLeft() , TypeTemplateParamDecl::printLeft() , UnnamedTypeName::printLeft() , VectorType::printLeft() , VendorExtQualType::printLeft() , QualType::printQuals() , ArrayType::printRight() , ConstrainedTypeTemplateParamDecl::printRight() , ForwardTemplateReference::printRight() , FunctionEncoding::printRight() , FunctionType::printRight() , NonTypeTemplateParamDecl::printRight() , ParameterPack::printRight() , PointerToMemberType::printRight() , PointerType::printRight() , QualType::printRight() , ReferenceType::printRight() , TemplateParamPackDecl::printRight() , TemplateTemplateParamDecl::printRight() , and TypeTemplateParamDecl::printRight() . Member Data Documentation ◆  ArrayCache Cache Node::ArrayCache protected Track if this node is a (possibly qualified) array type. This can affect how we format the output string. Definition at line 214 of file ItaniumDemangle.h . Referenced by getArrayCache() , hasArray() , Node() , and ParameterPack::ParameterPack() . ◆  FunctionCache Cache Node::FunctionCache protected Track if this node is a (possibly qualified) function type. This can affect how we format the output string. Definition at line 218 of file ItaniumDemangle.h . Referenced by getFunctionCache() , hasFunction() , Node() , and ParameterPack::ParameterPack() . ◆  RHSComponentCache Cache Node::RHSComponentCache protected Tracks if this node has a component on its right side, in which case we need to call printRight. Definition at line 210 of file ItaniumDemangle.h . Referenced by getRHSComponentCache() , hasRHSComponent() , Node() , ParameterPack::ParameterPack() , and print() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://www.php.net/manual/zh/intro.tokenizer.php | PHP: 简介 - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box 安装/配置 » « Tokenizer PHP 手册 函数参考 其它基本扩展 Tokenizer 切换语言: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other 简介 tokenizer 函数为嵌入在 Zend 引擎中的 PHP tokenizer 提供了接口。使用这些函数,可以编写自己的 PHP 源代码分析或修改工具,而无需在词法级别处理语言规范。 参阅 记号附录 。 发现了问题? 了解如何改进此页面 • 提交拉取请求 • 报告一个错误 + 添加备注 用户贡献的备注 此页面尚无用户贡献的备注。 Tokenizer 简介 安装/配置 预定义常量 示例 PhpToken Tokenizer 函数 Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://pages.awscloud.com/solutions/case-studies/?nc2=h_mo | AWS Support and Customer Service Contact Info | Amazon Web Services Skip to main content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Support › Contact AWS Contact AWS General support for sales, compliance, and subscribers Want to speak with an AWS sales specialist? Get in touch Chat online or talk by phone Connect with support directly Monday through Friday Request form Request AWS sales support Submit a sales support form Compliance support Request support related to AWS compliance Connect with AWS compliance support Subscriber support services Technical support Support for service related technical issues. Unavailable under the Basic Support Plan. Sign in and submit request Account or billing support Assistance with account and billing related inquiries Sign in to request Wrongful charges support Received a bill for AWS, but don't have an AWS account? Learn more Support plans Learn about AWS support plan options See Premium Support options AWS sign-in resources See additional resources for issues related to logging into the console Help signing in to the console Need assistance to sign in to the AWS Management Console? View documentation Trouble shoot your sign-in issue Tried sign in, but the credentials didn’t work? Or don’t have the credentials to access AWS root user account? View solutions Help with multi-factor authentication (MFA) issues Lost or unusable Multi-Factor Authentication (MFA) device View solution Still unable to sign in to your AWS account? If you are still unable to log into your AWS account please fill out this form. View form Additional resources Self-service re:Post provides access to curated knowledge and a vibrant community that helps you become even more successful on AWS View AWS re:Post Service limit increases Need to increase to service limit? Fill out a quick request form Sign in to request Report abuse Report abusive activity from Amazon Web Services Resources Report suspected abuse Amazon.com support Request Kindle or Amazon.com support View on amazon.com Did you find what you were looking for today? Let us know so we can improve the quality of the content on our pages Yes No Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms Cookie Preferences © 2026, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:30:39 |
https://www.php.net/x-myracloud-5958a2bbbed300a9b9ac631223924e0b/1768296252.421 | PHP update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box A popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world. What's new in 8.5 Download 8.5.1 · Changelog · Upgrading 8.4.16 · Changelog · Upgrading 8.3.29 · Changelog · Upgrading 8.2.30 · Changelog · Upgrading 18 Dec 2025 PHP 8.1.34 Released! The PHP development team announces the immediate availability of PHP 8.1.34. This is a security release. All PHP 8.1 users are encouraged to upgrade to this version. For source downloads of PHP 8.1.34 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.4.16 Released! The PHP development team announces the immediate availability of PHP 8.4.16. This is a security release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.16 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.2.30 Released! The PHP development team announces the immediate availability of PHP 8.2.30. This is a security release. All PHP 8.2 users are encouraged to upgrade to this version. For source downloads of PHP 8.2.30 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.3.29 Released! The PHP development team announces the immediate availability of PHP 8.3.29. This is a security release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.29 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.5.1 Released! The PHP development team announces the immediate availability of PHP 8.5.1. This is a security release. All PHP 8.5 users are encouraged to upgrade to this version. For source downloads of PHP 8.5.1 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.5.0 Released! The PHP development team announces the immediate availability of PHP 8.5.0. This release marks the latest minor release of the PHP language. PHP 8.5 comes with numerous improvements and new features such as: New "URI" extension New pipe operator (|>) Clone With New #[\NoDiscard] attribute Support for closures, casts, and first class callables in constant expressions And much much more... For source downloads of PHP 8.5.0 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . The migration guide is available in the PHP Manual. Please consult it for the detailed list of new features and backward incompatible changes. Kudos to all the contributors and supporters! 20 Nov 2025 PHP 8.4.15 Released! The PHP development team announces the immediate availability of PHP 8.4.15. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.15 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.3.28 Released! The PHP development team announces the immediate availability of PHP 8.3.28. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.28 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 13 Nov 2025 PHP 8.5.0 RC 5 available for testing The PHP team is pleased to announce the fifth release candidate of PHP 8.5.0, RC 5. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC5, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 06 Nov 2025 PHP 8.5.0 RC4 available for testing The PHP team is pleased to announce the final planned release candidate of PHP 8.5.0, RC 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC4, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 23 Oct 2025 PHP 8.3.27 Released! The PHP development team announces the immediate availability of PHP 8.3.27. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.27 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.4.14 Released! The PHP development team announces the immediate availability of PHP 8.4.14. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.14 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.5.0 RC 3 available for testing The PHP team is pleased to announce the third release candidate of PHP 8.5.0, RC 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC4, planned for 6 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 09 Oct 2025 PHP 8.5.0 RC 2 available for testing The PHP team is pleased to announce the second release candidate of PHP 8.5.0, RC 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC2, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC3, planned for 23 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.5.0 RC 1 available for testing The PHP team is pleased to announce the first release candidate of PHP 8.5.0, RC 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC1, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC2, planned for 9 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.3.26 Released! The PHP development team announces the immediate availability of PHP 8.3.26. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.26 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 25 Sep 2025 PHP 8.4.13 Released! The PHP development team announces the immediate availability of PHP 8.4.13. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.13 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 11 Sep 2025 PHP 8.5.0 Beta 3 available for testing The PHP team is pleased to announce the third beta release of PHP 8.5.0, Beta 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC1, planned for 25 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.5.0 Beta 2 available for testing The PHP team is pleased to announce the second beta release of PHP 8.5.0, Beta 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 2 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 3, planned for 11 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.3.25 Released! The PHP development team announces the immediate availability of PHP 8.3.25. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.25 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 28 Aug 2025 PHP 8.4.12 Released! The PHP development team announces the immediate availability of PHP 8.4.12. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.12 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 14 Aug 2025 PHP 8.5.0 Beta 1 available for testing The PHP team is pleased to announce the first beta release of PHP 8.5.0, Beta 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 1 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 2, planned for 28 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 01 Aug 2025 PHP 8.5.0 Alpha 4 available for testing The PHP team is pleased to announce the third testing release of PHP 8.5.0, Alpha 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Alpha 4 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 1, planned for 14 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 31 Jul 2025 PHP 8.4.11 Released! The PHP development team announces the immediate availability of PHP 8.4.11. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.11 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 31 Jul 2025 PHP 8.3.24 Released! The PHP development team announces the immediate availability of PHP 8.3.24. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.24 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . Older News Entries The PHP Foundation The PHP Foundation is a collective of people and organizations, united in the mission to ensure the long-term prosperity of the PHP language. Donate Upcoming conferences International PHP Conference Berlin 2026 Laravel Live Japan Conferences calling for papers Dutch PHP Conference 2026 User Group Events Special Thanks Social media @official_php @php@fosstodon.org @phpnet Copyright © 2001-2026 The PHP Group My PHP.net Contact Other PHP.net sites Privacy policy View Source ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classPointerToMemberType.html#ae081cb834243c8f9869251f100099891 | LLVM: PointerToMemberType Class Reference LLVM  22.0.0git Public Member Functions | List of all members PointerToMemberType Class Reference final #include " llvm/Demangle/ItaniumDemangle.h " Inheritance diagram for PointerToMemberType: This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead. [ legend ] Public Member Functions   PointerToMemberType ( const Node *ClassType_, const Node *MemberType_) template<typename Fn> void  match (Fn F ) const bool   hasRHSComponentSlow ( OutputBuffer &OB) const override void  printLeft ( OutputBuffer &OB) const override void  printRight ( OutputBuffer &OB) const override Public Member Functions inherited from Node   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Additional Inherited Members Public Types inherited from Node enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Protected Attributes inherited from Node Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Detailed Description Definition at line 765 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  PointerToMemberType() PointerToMemberType::PointerToMemberType ( const Node * ClassType_ , const Node * MemberType_  ) inline Definition at line 770 of file ItaniumDemangle.h . References Node::getRHSComponentCache() , and Node::Node() . Member Function Documentation ◆  hasRHSComponentSlow() bool PointerToMemberType::hasRHSComponentSlow ( OutputBuffer & OB ) const inline override virtual Reimplemented from Node . Definition at line 776 of file ItaniumDemangle.h . References Node::OutputBuffer . ◆  match() template<typename Fn> void PointerToMemberType::match ( Fn F ) const inline Definition at line 774 of file ItaniumDemangle.h . References F . ◆  printLeft() void PointerToMemberType::printLeft ( OutputBuffer & OB ) const inline override virtual Implements Node . Definition at line 780 of file ItaniumDemangle.h . References Node::OutputBuffer . ◆  printRight() void PointerToMemberType::printRight ( OutputBuffer & OB ) const inline override virtual Reimplemented from Node . Definition at line 790 of file ItaniumDemangle.h . References Node::OutputBuffer . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classObjCProtoName-members.html | LLVM: Member List LLVM  22.0.0git ObjCProtoName Member List This is the complete list of members for ObjCProtoName , including all inherited members. ArrayCache Node protected Cache enum name Node dump () const Node FunctionCache Node protected getArrayCache () const Node inline getBaseName () const Node inline virtual getFunctionCache () const Node inline getKind () const Node inline getPrecedence () const Node inline getProtocol () const ObjCProtoName inline getRHSComponentCache () const Node inline getSyntaxNode (OutputBuffer &) const Node inline virtual hasArray (OutputBuffer &OB) const Node inline hasArraySlow (OutputBuffer &) const Node inline virtual hasFunction (OutputBuffer &OB) const Node inline hasFunctionSlow (OutputBuffer &) const Node inline virtual hasRHSComponent (OutputBuffer &OB) const Node inline hasRHSComponentSlow (OutputBuffer &) const Node inline virtual isObjCObject () const ObjCProtoName inline Kind enum name Node match (Fn F) const ObjCProtoName inline Node (Kind K_, Prec Precedence_=Prec::Primary, Cache RHSComponentCache_=Cache::No, Cache ArrayCache_=Cache::No, Cache FunctionCache_=Cache::No) Node inline Node (Kind K_, Cache RHSComponentCache_, Cache ArrayCache_=Cache::No, Cache FunctionCache_=Cache::No) Node inline ObjCProtoName (const Node *Ty_, std::string_view Protocol_) ObjCProtoName inline Prec enum name Node print (OutputBuffer &OB) const Node inline printAsOperand (OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const Node inline printInitListAsType (OutputBuffer &, const NodeArray &) const Node inline virtual printLeft (OutputBuffer &OB) const override ObjCProtoName inline virtual RHSComponentCache Node protected visit (Fn F) const Node ~Node ()=default Node virtual Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/structNestedName-members.html | LLVM: Member List LLVM  22.0.0git NestedName Member List This is the complete list of members for NestedName , including all inherited members. ArrayCache Node protected Cache enum name Node dump () const Node FunctionCache Node protected getArrayCache () const Node inline getBaseName () const override NestedName inline virtual getFunctionCache () const Node inline getKind () const Node inline getPrecedence () const Node inline getRHSComponentCache () const Node inline getSyntaxNode (OutputBuffer &) const Node inline virtual hasArray (OutputBuffer &OB) const Node inline hasArraySlow (OutputBuffer &) const Node inline virtual hasFunction (OutputBuffer &OB) const Node inline hasFunctionSlow (OutputBuffer &) const Node inline virtual hasRHSComponent (OutputBuffer &OB) const Node inline hasRHSComponentSlow (OutputBuffer &) const Node inline virtual Kind enum name Node match (Fn F) const NestedName inline Name NestedName NestedName (Node *Qual_, Node *Name_) NestedName inline Node (Kind K_, Prec Precedence_=Prec::Primary, Cache RHSComponentCache_=Cache::No, Cache ArrayCache_=Cache::No, Cache FunctionCache_=Cache::No) Node inline Node (Kind K_, Cache RHSComponentCache_, Cache ArrayCache_=Cache::No, Cache FunctionCache_=Cache::No) Node inline Prec enum name Node print (OutputBuffer &OB) const Node inline printAsOperand (OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const Node inline printInitListAsType (OutputBuffer &, const NodeArray &) const Node inline virtual printLeft (OutputBuffer &OB) const override NestedName inline virtual Qual NestedName RHSComponentCache Node protected visit (Fn F) const Node ~Node ()=default Node virtual Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/InlineOrder_8cpp.html#a7ee6f0cb51c3b9056199e9a0001fe8c3a6f6cb72d544962fa333e2e34ce64f719 | LLVM: lib/Analysis/InlineOrder.cpp File Reference LLVM  22.0.0git lib Analysis Macros | Enumerations | Variables InlineOrder.cpp File Reference #include " llvm/Analysis/InlineOrder.h " #include " llvm/Analysis/AssumptionCache.h " #include " llvm/Analysis/BlockFrequencyInfo.h " #include " llvm/Analysis/GlobalsModRef.h " #include " llvm/Analysis/InlineAdvisor.h " #include " llvm/Analysis/InlineCost.h " #include " llvm/Analysis/OptimizationRemarkEmitter.h " #include " llvm/Analysis/ProfileSummaryInfo.h " #include " llvm/Analysis/TargetLibraryInfo.h " #include " llvm/Analysis/TargetTransformInfo.h " #include " llvm/Support/CommandLine.h " Go to the source code of this file. Macros #define  DEBUG_TYPE    "inline-order" Enumerations enum class   InlinePriorityMode : int { Size , Cost , CostBenefit , ML } Variables static cl::opt < InlinePriorityMode >  UseInlinePriority ("inline-priority-mode", cl::init( InlinePriorityMode::Size ), cl::Hidden, cl::desc ("Choose the priority mode to use in module inline"), cl::values( clEnumValN ( InlinePriorityMode::Size , "size", "Use callee size priority."), clEnumValN ( InlinePriorityMode::Cost , "cost", "Use inline cost priority."), clEnumValN ( InlinePriorityMode::CostBenefit , "cost-benefit", "Use cost-benefit ratio."), clEnumValN ( InlinePriorityMode::ML , "ml", "Use ML."))) static cl::opt < int >  ModuleInlinerTopPriorityThreshold ("module-inliner-top-priority-threshold", cl::Hidden, cl::init(0), cl::desc ("The cost threshold for call sites that get inlined without the " "cost-benefit analysis")) Macro Definition Documentation ◆  DEBUG_TYPE #define DEBUG_TYPE   "inline-order" Definition at line 23 of file InlineOrder.cpp . Enumeration Type Documentation ◆  InlinePriorityMode enum class InlinePriorityMode : int strong Enumerator Size  Cost  CostBenefit  ML  Definition at line 25 of file InlineOrder.cpp . Variable Documentation ◆  ModuleInlinerTopPriorityThreshold cl::opt < int > ModuleInlinerTopPriorityThreshold("module-inliner-top-priority-threshold", cl::Hidden, cl::init(0), cl::desc ("The cost threshold for call sites that get inlined without the " "cost-benefit analysis")) ( "module-inliner-top-priority-threshold" , cl::Hidden , cl::init(0) , cl::desc ("The cost threshold for call sites that get inlined without the " "cost-benefit analysis")  ) static ◆  UseInlinePriority cl::opt < InlinePriorityMode > UseInlinePriority("inline-priority-mode", cl::init( InlinePriorityMode::Size ), cl::Hidden, cl::desc ("Choose the priority mode to use in module inline"), cl::values( clEnumValN ( InlinePriorityMode::Size , "size", "Use callee size priority."), clEnumValN ( InlinePriorityMode::Cost , "cost", "Use inline cost priority."), clEnumValN ( InlinePriorityMode::CostBenefit , "cost-benefit", "Use cost-benefit ratio."), clEnumValN ( InlinePriorityMode::ML , "ml", "Use ML."))) ( "inline-priority-mode" , cl::init( InlinePriorityMode::Size ) , cl::Hidden , cl::desc ("Choose the priority mode to use in module inline") , cl::values( clEnumValN ( InlinePriorityMode::Size , "size", "Use callee size priority."), clEnumValN ( InlinePriorityMode::Cost , "cost", "Use inline cost priority."), clEnumValN ( InlinePriorityMode::CostBenefit , "cost-benefit", "Use cost-benefit ratio."), clEnumValN ( InlinePriorityMode::ML , "ml", "Use ML."))  ) static Referenced by llvm::getDefaultInlineOrder() . Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/DemangleConfig_8h.html#a5b2ab89559cfa9c7fbfd635bec59e42d | LLVM: include/llvm/Demangle/DemangleConfig.h File Reference LLVM  22.0.0git include llvm Demangle Macros DemangleConfig.h File Reference #include "llvm/Config/llvm-config.h" #include <cassert> Go to the source code of this file. Macros #define  __has_feature (x) #define  __has_cpp_attribute (x) #define  __has_attribute (x) #define  __has_builtin (x) #define  DEMANGLE_GNUC_PREREQ (maj, min, patch) #define  DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_UNREACHABLE #define  DEMANGLE_ATTRIBUTE_NOINLINE #define  DEMANGLE_DUMP_METHOD     DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_FALLTHROUGH #define  DEMANGLE_ASSERT (__expr, __msg) #define  DEMANGLE_NAMESPACE_BEGIN    namespace llvm { namespace itanium_demangle { #define  DEMANGLE_NAMESPACE_END    } } #define  DEMANGLE_ABI   DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Macro Definition Documentation ◆  __has_attribute #define __has_attribute ( x ) Value: 0 Definition at line 30 of file DemangleConfig.h . ◆  __has_builtin #define __has_builtin ( x ) Value: 0 Definition at line 34 of file DemangleConfig.h . ◆  __has_cpp_attribute #define __has_cpp_attribute ( x ) Value: 0 Definition at line 26 of file DemangleConfig.h . ◆  __has_feature #define __has_feature ( x ) Value: 0 Definition at line 22 of file DemangleConfig.h . ◆  DEMANGLE_ABI #define DEMANGLE_ABI DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Definition at line 115 of file DemangleConfig.h . Referenced by llvm::ms_demangle::Node::output() , parse_discriminator() , and llvm::ms_demangle::Demangler::~Demangler() . ◆  DEMANGLE_ASSERT #define DEMANGLE_ASSERT ( __expr , __msg  ) Value: assert ((__expr) && (__msg)) assert assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!") Definition at line 94 of file DemangleConfig.h . Referenced by OutputBuffer::back() , PODSmallVector< Node *, 8 >::back() , ExplicitObjectParameter::ExplicitObjectParameter() , SpecialSubstitution::getBaseName() , AbstractManglingParser< Derived, Alloc >::OperatorInfo::getSymbol() , OutputBuffer::insert() , PODSmallVector< Node *, 8 >::operator[]() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnresolvedName() , PODSmallVector< Node *, 8 >::pop_back() , AbstractManglingParser< Derived, Alloc >::popTrailingNodeArray() , PODSmallVector< Node *, 8 >::shrinkToSize() , Node::visit() , and AbstractManglingParser< Derived, Alloc >::ScopedTemplateParamList::~ScopedTemplateParamList() . ◆  DEMANGLE_ATTRIBUTE_NOINLINE #define DEMANGLE_ATTRIBUTE_NOINLINE Definition at line 69 of file DemangleConfig.h . ◆  DEMANGLE_ATTRIBUTE_USED #define DEMANGLE_ATTRIBUTE_USED Definition at line 53 of file DemangleConfig.h . ◆  DEMANGLE_DUMP_METHOD #define DEMANGLE_DUMP_METHOD    DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED Definition at line 73 of file DemangleConfig.h . Referenced by Node::dump() . ◆  DEMANGLE_FALLTHROUGH #define DEMANGLE_FALLTHROUGH Definition at line 85 of file DemangleConfig.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseType() . ◆  DEMANGLE_GNUC_PREREQ #define DEMANGLE_GNUC_PREREQ ( maj , min , patch  ) Value: 0 Definition at line 46 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_BEGIN #define DEMANGLE_NAMESPACE_BEGIN   namespace llvm { namespace itanium_demangle { Definition at line 97 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_END #define DEMANGLE_NAMESPACE_END   } } Definition at line 98 of file DemangleConfig.h . ◆  DEMANGLE_UNREACHABLE #define DEMANGLE_UNREACHABLE Definition at line 61 of file DemangleConfig.h . Referenced by demanglePointerCVQualifiers() , ExpandedSpecialSubstitution::getBaseName() , and AbstractManglingParser< Derived, Alloc >::parseExpr() . Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/DemangleConfig_8h.html#a54d2d7742701f3f112afbcd8d4f9ccdb | LLVM: include/llvm/Demangle/DemangleConfig.h File Reference LLVM  22.0.0git include llvm Demangle Macros DemangleConfig.h File Reference #include "llvm/Config/llvm-config.h" #include <cassert> Go to the source code of this file. Macros #define  __has_feature (x) #define  __has_cpp_attribute (x) #define  __has_attribute (x) #define  __has_builtin (x) #define  DEMANGLE_GNUC_PREREQ (maj, min, patch) #define  DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_UNREACHABLE #define  DEMANGLE_ATTRIBUTE_NOINLINE #define  DEMANGLE_DUMP_METHOD     DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_FALLTHROUGH #define  DEMANGLE_ASSERT (__expr, __msg) #define  DEMANGLE_NAMESPACE_BEGIN    namespace llvm { namespace itanium_demangle { #define  DEMANGLE_NAMESPACE_END    } } #define  DEMANGLE_ABI   DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Macro Definition Documentation ◆  __has_attribute #define __has_attribute ( x ) Value: 0 Definition at line 30 of file DemangleConfig.h . ◆  __has_builtin #define __has_builtin ( x ) Value: 0 Definition at line 34 of file DemangleConfig.h . ◆  __has_cpp_attribute #define __has_cpp_attribute ( x ) Value: 0 Definition at line 26 of file DemangleConfig.h . ◆  __has_feature #define __has_feature ( x ) Value: 0 Definition at line 22 of file DemangleConfig.h . ◆  DEMANGLE_ABI #define DEMANGLE_ABI DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Definition at line 115 of file DemangleConfig.h . Referenced by llvm::ms_demangle::Node::output() , parse_discriminator() , and llvm::ms_demangle::Demangler::~Demangler() . ◆  DEMANGLE_ASSERT #define DEMANGLE_ASSERT ( __expr , __msg  ) Value: assert ((__expr) && (__msg)) assert assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!") Definition at line 94 of file DemangleConfig.h . Referenced by OutputBuffer::back() , PODSmallVector< Node *, 8 >::back() , ExplicitObjectParameter::ExplicitObjectParameter() , SpecialSubstitution::getBaseName() , AbstractManglingParser< Derived, Alloc >::OperatorInfo::getSymbol() , OutputBuffer::insert() , PODSmallVector< Node *, 8 >::operator[]() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnresolvedName() , PODSmallVector< Node *, 8 >::pop_back() , AbstractManglingParser< Derived, Alloc >::popTrailingNodeArray() , PODSmallVector< Node *, 8 >::shrinkToSize() , Node::visit() , and AbstractManglingParser< Derived, Alloc >::ScopedTemplateParamList::~ScopedTemplateParamList() . ◆  DEMANGLE_ATTRIBUTE_NOINLINE #define DEMANGLE_ATTRIBUTE_NOINLINE Definition at line 69 of file DemangleConfig.h . ◆  DEMANGLE_ATTRIBUTE_USED #define DEMANGLE_ATTRIBUTE_USED Definition at line 53 of file DemangleConfig.h . ◆  DEMANGLE_DUMP_METHOD #define DEMANGLE_DUMP_METHOD    DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED Definition at line 73 of file DemangleConfig.h . Referenced by Node::dump() . ◆  DEMANGLE_FALLTHROUGH #define DEMANGLE_FALLTHROUGH Definition at line 85 of file DemangleConfig.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseType() . ◆  DEMANGLE_GNUC_PREREQ #define DEMANGLE_GNUC_PREREQ ( maj , min , patch  ) Value: 0 Definition at line 46 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_BEGIN #define DEMANGLE_NAMESPACE_BEGIN   namespace llvm { namespace itanium_demangle { Definition at line 97 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_END #define DEMANGLE_NAMESPACE_END   } } Definition at line 98 of file DemangleConfig.h . ◆  DEMANGLE_UNREACHABLE #define DEMANGLE_UNREACHABLE Definition at line 61 of file DemangleConfig.h . Referenced by demanglePointerCVQualifiers() , ExpandedSpecialSubstitution::getBaseName() , and AbstractManglingParser< Derived, Alloc >::parseExpr() . Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Exercise:-Add-regression-lines | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://sujaypillai.dev/2015/09/2015-09-18-aikau-auditing-reporting/ | Aikau Audit Report | Sujay Pillai Sujay Pillai Posts Tags Categories About Sujay Pillai Posts Tags Categories About Aikau Audit Report Sujay Pillai included in Alfresco 2015-09-18 about 506 words 3 min EisenVault takes away the hassle of managing documents by storing them in both electronic and physical forms, enabling smart-search and deploying quick retrieval measures. Our innovative cloud-based document management system can be used in multiple industry sectors, and caters to specific requirements of various job roles. Our vision - to be your preferred partner for electronic and physical document management. This is EisenVault’s first Aikau plugin and we would like to share our experience building it. While during the days when people used Alfresco Explorer there was an option to view the audit trail for a document using the show_audit.ftl by selecting “Preview in Template” . Below is a screenshot of how it looked - But there is no such option in Alfresco Share to view those audit data, so I thought of building it. Auditing is by default enabled in Alfresco but the data generation for the same is disabled and to enable this you would have to put in the below property in alfresco-global.properties. 1 audit.alfresco-access.enabled=true You can check the status for auditing by issuing the command: 1 curl -u admin:password "http://localhost:8080/alfresco/service/api/audit/control" On issuing the above command you would get a JSON response something similar - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 { "enabled" : true , "applications" : [ { "name" : "Alfresco Tagging Service" , "path" : "/tagging" , "enabled" : true } , { "name" : "alfresco-access" , "path" : "/alfresco-access" , "enabled" : true } ] } You can also query to retrieve the audit events: 1 curl -u admin:password "http://localhost:8080/alfresco/service/api/audit/query/alfresco-access?limit=2" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 { "count" : 2 , "entries" : [ { "id" : 1 , "application" : "alfresco-access" , "user" : "admin" , "time" : "2015-09-16T13:48:08.796+08:00" , "values" : null }, { "id" : 2 , "application" : "alfresco-access" , "user" : "admin" , "time" : "2015-09-16T13:48:09.560+08:00" , "values" : null } ] } If you looking for more information about Alfresco Audting you should definitely look here Aikau Audit Report page The new Aikau Audit report page lets you view the audit trail for each document in the repository as shown below: You can access this page either from the document library action OR from the Document Actions section from the document details page: | How does it work? The AlfList widget makes a call to webscript NodeAuditTrailWebScript with help of the attribute loadDataPublishTopic via the CrudService (using the “ ALF_CRUD_GET_ALL ” topic) which take the nodeRef as a parameter and this in turn returns the data in JSON format. Now to render the list what AlfList loads we need to create a view which is done with the help of AlfListView . As the list contains five columns we would be adding same number of HeaderCell for the attribute widgetsForHeader . Each row in the data will be represented by Row and each Cell will hold Property to render the value for respective Cell . As the last column “ Audit Entry Values ” holds multiple values the Property widget need to be overridden and you may find this in Property.js You may find the complete source code for this addon on Github This article is updated with 2015-09-18 alfresco aikau Back | Home Alfresco Multi Folder Template Selection Downgrading AMP version in Alfresco Powered by Hugo | Theme - LoveIt 2018 - 2021 Sujay Pillai | CC BY-NC 4.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#A-small-exercise | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/DemangleConfig_8h.html#ac71d1b2a381f0070e426cf362f0ef7e2 | LLVM: include/llvm/Demangle/DemangleConfig.h File Reference LLVM  22.0.0git include llvm Demangle Macros DemangleConfig.h File Reference #include "llvm/Config/llvm-config.h" #include <cassert> Go to the source code of this file. Macros #define  __has_feature (x) #define  __has_cpp_attribute (x) #define  __has_attribute (x) #define  __has_builtin (x) #define  DEMANGLE_GNUC_PREREQ (maj, min, patch) #define  DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_UNREACHABLE #define  DEMANGLE_ATTRIBUTE_NOINLINE #define  DEMANGLE_DUMP_METHOD     DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_FALLTHROUGH #define  DEMANGLE_ASSERT (__expr, __msg) #define  DEMANGLE_NAMESPACE_BEGIN    namespace llvm { namespace itanium_demangle { #define  DEMANGLE_NAMESPACE_END    } } #define  DEMANGLE_ABI   DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Macro Definition Documentation ◆  __has_attribute #define __has_attribute ( x ) Value: 0 Definition at line 30 of file DemangleConfig.h . ◆  __has_builtin #define __has_builtin ( x ) Value: 0 Definition at line 34 of file DemangleConfig.h . ◆  __has_cpp_attribute #define __has_cpp_attribute ( x ) Value: 0 Definition at line 26 of file DemangleConfig.h . ◆  __has_feature #define __has_feature ( x ) Value: 0 Definition at line 22 of file DemangleConfig.h . ◆  DEMANGLE_ABI #define DEMANGLE_ABI DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Definition at line 115 of file DemangleConfig.h . Referenced by llvm::ms_demangle::Node::output() , parse_discriminator() , and llvm::ms_demangle::Demangler::~Demangler() . ◆  DEMANGLE_ASSERT #define DEMANGLE_ASSERT ( __expr , __msg  ) Value: assert ((__expr) && (__msg)) assert assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!") Definition at line 94 of file DemangleConfig.h . Referenced by OutputBuffer::back() , PODSmallVector< Node *, 8 >::back() , ExplicitObjectParameter::ExplicitObjectParameter() , SpecialSubstitution::getBaseName() , AbstractManglingParser< Derived, Alloc >::OperatorInfo::getSymbol() , OutputBuffer::insert() , PODSmallVector< Node *, 8 >::operator[]() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnresolvedName() , PODSmallVector< Node *, 8 >::pop_back() , AbstractManglingParser< Derived, Alloc >::popTrailingNodeArray() , PODSmallVector< Node *, 8 >::shrinkToSize() , Node::visit() , and AbstractManglingParser< Derived, Alloc >::ScopedTemplateParamList::~ScopedTemplateParamList() . ◆  DEMANGLE_ATTRIBUTE_NOINLINE #define DEMANGLE_ATTRIBUTE_NOINLINE Definition at line 69 of file DemangleConfig.h . ◆  DEMANGLE_ATTRIBUTE_USED #define DEMANGLE_ATTRIBUTE_USED Definition at line 53 of file DemangleConfig.h . ◆  DEMANGLE_DUMP_METHOD #define DEMANGLE_DUMP_METHOD    DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED Definition at line 73 of file DemangleConfig.h . Referenced by Node::dump() . ◆  DEMANGLE_FALLTHROUGH #define DEMANGLE_FALLTHROUGH Definition at line 85 of file DemangleConfig.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseType() . ◆  DEMANGLE_GNUC_PREREQ #define DEMANGLE_GNUC_PREREQ ( maj , min , patch  ) Value: 0 Definition at line 46 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_BEGIN #define DEMANGLE_NAMESPACE_BEGIN   namespace llvm { namespace itanium_demangle { Definition at line 97 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_END #define DEMANGLE_NAMESPACE_END   } } Definition at line 98 of file DemangleConfig.h . ◆  DEMANGLE_UNREACHABLE #define DEMANGLE_UNREACHABLE Definition at line 61 of file DemangleConfig.h . Referenced by demanglePointerCVQualifiers() , ExpandedSpecialSubstitution::getBaseName() , and AbstractManglingParser< Derived, Alloc >::parseExpr() . Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNode.html#a1741d927ae4f746a135ec7557c5f8a8ca19c6e8d6e2caeaff0ac8881e05c25010 | LLVM: Node Class Reference LLVM  22.0.0git Public Types | Public Member Functions | Protected Attributes | Friends | List of all members Node Class Reference abstract #include " llvm/Demangle/ItaniumDemangle.h " Inherited by FloatLiteralImpl< float > , FloatLiteralImpl< double > , FloatLiteralImpl< long double > , AbiTagAttr , ArraySubscriptExpr , ArrayType , BinaryExpr , BinaryFPType , BitIntType , BoolExpr , BracedExpr , BracedRangeExpr , CallExpr , CastExpr , ClosureTypeName , ConditionalExpr , ConstrainedTypeTemplateParamDecl , ConversionExpr , ConversionOperatorType , CtorDtorName , CtorVtableSpecialName , DeleteExpr , DotSuffix , DtorName , DynamicExceptionSpec , ElaboratedTypeSpefType , EnableIfAttr , EnclosingExpr , EnumLiteral , ExpandedSpecialSubstitution , ExplicitObjectParameter , ExprRequirement , FloatLiteralImpl< Float > , FoldExpr , ForwardTemplateReference , FunctionEncoding , FunctionParam , FunctionType , GlobalQualifiedName , InitListExpr , IntegerLiteral , LambdaExpr , LiteralOperator , LocalName , MemberExpr , MemberLikeFriendName , ModuleEntity , ModuleName , NameType , NameWithTemplateArgs , NestedName , NestedRequirement , NewExpr , NodeArrayNode , NoexceptSpec , NonTypeTemplateParamDecl , ObjCProtoName , ParameterPack , ParameterPackExpansion , PixelVectorType , PointerToMemberConversionExpr , PointerToMemberType , PointerType , PostfixExpr , PostfixQualifiedType , PrefixExpr , QualType , QualifiedName , ReferenceType , RequiresExpr , SizeofParamPackExpr , SpecialName , StringLiteral , StructuredBindingName , SubobjectExpr , SyntheticTemplateParamName , TemplateArgs , TemplateArgumentPack , TemplateParamPackDecl , TemplateParamQualifiedArg , TemplateTemplateParamDecl , ThrowExpr , TransformedType , TypeRequirement , TypeTemplateParamDecl , UnnamedTypeName , VectorType , and VendorExtQualType . Public Types enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Public Member Functions   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Protected Attributes Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Friends class  OutputBuffer Detailed Description Definition at line 166 of file ItaniumDemangle.h . Member Enumeration Documentation ◆  Cache enum class Node::Cache : uint8_t strong Three-way bool to track a cached value. Unknown is possible if this node has an unexpanded parameter pack below it that may affect this cache. Enumerator Yes  No  Unknown  Definition at line 175 of file ItaniumDemangle.h . ◆  Kind enum Node::Kind : uint8_t Definition at line 168 of file ItaniumDemangle.h . ◆  Prec enum class Node::Prec : uint8_t strong Operator precedence for expression nodes. Used to determine required parens in expression emission. Enumerator Primary  Postfix  Unary  Cast  PtrMem  Multiplicative  Additive  Shift  Spaceship  Relational  Equality  And  Xor  Ior  AndIf  OrIf  Conditional  Assign  Comma  Default  Definition at line 179 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  Node() [1/2] Node::Node ( Kind K_ , Prec Precedence_ = Prec::Primary , Cache RHSComponentCache_ = Cache::No , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 221 of file ItaniumDemangle.h . References ArrayCache , FunctionCache , No , Primary , and RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , ArraySubscriptExpr::ArraySubscriptExpr() , ArrayType::ArrayType() , BinaryExpr::BinaryExpr() , BinaryFPType::BinaryFPType() , BitIntType::BitIntType() , BoolExpr::BoolExpr() , BracedExpr::BracedExpr() , BracedRangeExpr::BracedRangeExpr() , CallExpr::CallExpr() , CastExpr::CastExpr() , ClosureTypeName::ClosureTypeName() , ConditionalExpr::ConditionalExpr() , ConstrainedTypeTemplateParamDecl::ConstrainedTypeTemplateParamDecl() , ConversionExpr::ConversionExpr() , ConversionOperatorType::ConversionOperatorType() , CtorDtorName::CtorDtorName() , CtorVtableSpecialName::CtorVtableSpecialName() , DeleteExpr::DeleteExpr() , DotSuffix::DotSuffix() , DtorName::DtorName() , DynamicExceptionSpec::DynamicExceptionSpec() , ElaboratedTypeSpefType::ElaboratedTypeSpefType() , EnableIfAttr::EnableIfAttr() , EnclosingExpr::EnclosingExpr() , EnumLiteral::EnumLiteral() , ExpandedSpecialSubstitution::ExpandedSpecialSubstitution() , ExplicitObjectParameter::ExplicitObjectParameter() , ExprRequirement::ExprRequirement() , FloatLiteralImpl< float >::FloatLiteralImpl() , FoldExpr::FoldExpr() , ForwardTemplateReference::ForwardTemplateReference() , FunctionEncoding::FunctionEncoding() , FunctionParam::FunctionParam() , FunctionType::FunctionType() , TemplateParamQualifiedArg::getArg() , FunctionEncoding::getAttrs() , VectorType::getBaseType() , ParameterPackExpansion::getChild() , QualType::getChild() , VectorType::getDimension() , FunctionEncoding::getName() , PointerType::getPointee() , FunctionEncoding::getRequires() , FunctionEncoding::getReturnType() , ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , VendorExtQualType::getTA() , VendorExtQualType::getTy() , GlobalQualifiedName::GlobalQualifiedName() , InitListExpr::InitListExpr() , IntegerLiteral::IntegerLiteral() , LambdaExpr::LambdaExpr() , LiteralOperator::LiteralOperator() , LocalName::LocalName() , MemberExpr::MemberExpr() , MemberLikeFriendName::MemberLikeFriendName() , ModuleEntity::ModuleEntity() , ModuleName::ModuleName() , NameType::NameType() , NameWithTemplateArgs::NameWithTemplateArgs() , NestedName::NestedName() , NestedRequirement::NestedRequirement() , NewExpr::NewExpr() , Node() , NodeArrayNode::NodeArrayNode() , NoexceptSpec::NoexceptSpec() , NonTypeTemplateParamDecl::NonTypeTemplateParamDecl() , ObjCProtoName::ObjCProtoName() , ParameterPack::ParameterPack() , ParameterPackExpansion::ParameterPackExpansion() , PixelVectorType::PixelVectorType() , PointerToMemberConversionExpr::PointerToMemberConversionExpr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , PostfixExpr::PostfixExpr() , PostfixQualifiedType::PostfixQualifiedType() , PrefixExpr::PrefixExpr() , RequiresExpr::printLeft() , QualifiedName::QualifiedName() , QualType::QualType() , ReferenceType::ReferenceType() , RequiresExpr::RequiresExpr() , SizeofParamPackExpr::SizeofParamPackExpr() , SpecialName::SpecialName() , StringLiteral::StringLiteral() , StructuredBindingName::StructuredBindingName() , SubobjectExpr::SubobjectExpr() , SyntheticTemplateParamName::SyntheticTemplateParamName() , TemplateArgs::TemplateArgs() , TemplateArgumentPack::TemplateArgumentPack() , TemplateParamPackDecl::TemplateParamPackDecl() , TemplateParamQualifiedArg::TemplateParamQualifiedArg() , TemplateTemplateParamDecl::TemplateTemplateParamDecl() , ThrowExpr::ThrowExpr() , TransformedType::TransformedType() , TypeRequirement::TypeRequirement() , TypeTemplateParamDecl::TypeTemplateParamDecl() , UnnamedTypeName::UnnamedTypeName() , VectorType::VectorType() , and VendorExtQualType::VendorExtQualType() . ◆  Node() [2/2] Node::Node ( Kind K_ , Cache RHSComponentCache_ , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 226 of file ItaniumDemangle.h . References No , Node() , and Primary . ◆  ~Node() virtual Node::~Node ( ) virtual default Member Function Documentation ◆  dump() DEMANGLE_DUMP_METHOD void Node::dump ( ) const References DEMANGLE_DUMP_METHOD . Referenced by llvm::DAGTypeLegalizer::run() , and llvm::RISCVDAGToDAGISel::Select() . ◆  getArrayCache() Cache Node::getArrayCache ( ) const inline Definition at line 262 of file ItaniumDemangle.h . References ArrayCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getBaseName() virtual std::string_view Node::getBaseName ( ) const inline virtual Reimplemented in AbiTagAttr , ExpandedSpecialSubstitution , GlobalQualifiedName , MemberLikeFriendName , ModuleEntity , NameType , NameWithTemplateArgs , NestedName , QualifiedName , and SpecialSubstitution . Definition at line 299 of file ItaniumDemangle.h . ◆  getFunctionCache() Cache Node::getFunctionCache ( ) const inline Definition at line 263 of file ItaniumDemangle.h . References FunctionCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getKind() Kind Node::getKind ( ) const inline Definition at line 258 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseCtorDtorName() , AbstractManglingParser< Derived, Alloc >::parseNestedName() , AbstractManglingParser< Derived, Alloc >::parseTemplateArgs() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnscopedName() , NodeArray::printAsString() , and llvm::msgpack::Document::writeToBlob() . ◆  getPrecedence() Prec Node::getPrecedence ( ) const inline Definition at line 260 of file ItaniumDemangle.h . Referenced by ArraySubscriptExpr::match() , BinaryExpr::match() , CallExpr::match() , CastExpr::match() , ConditionalExpr::match() , ConversionExpr::match() , DeleteExpr::match() , EnclosingExpr::match() , MemberExpr::match() , NewExpr::match() , PointerToMemberConversionExpr::match() , PostfixExpr::match() , PrefixExpr::match() , printAsOperand() , ArraySubscriptExpr::printLeft() , BinaryExpr::printLeft() , ConditionalExpr::printLeft() , MemberExpr::printLeft() , PostfixExpr::printLeft() , and PrefixExpr::printLeft() . ◆  getRHSComponentCache() Cache Node::getRHSComponentCache ( ) const inline Definition at line 261 of file ItaniumDemangle.h . References RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , QualType::QualType() , and ReferenceType::ReferenceType() . ◆  getSyntaxNode() virtual const Node * Node::getSyntaxNode ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , and ParameterPack . Definition at line 271 of file ItaniumDemangle.h . References Node() , and OutputBuffer . ◆  hasArray() bool Node::hasArray ( OutputBuffer & OB ) const inline Definition at line 246 of file ItaniumDemangle.h . References ArrayCache , hasArraySlow() , OutputBuffer , Unknown , and Yes . ◆  hasArraySlow() virtual bool Node::hasArraySlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , ParameterPack , and QualType . Definition at line 266 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasArray() . ◆  hasFunction() bool Node::hasFunction ( OutputBuffer & OB ) const inline Definition at line 252 of file ItaniumDemangle.h . References FunctionCache , hasFunctionSlow() , OutputBuffer , Unknown , and Yes . ◆  hasFunctionSlow() virtual bool Node::hasFunctionSlow ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , and QualType . Definition at line 267 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasFunction() . ◆  hasRHSComponent() bool Node::hasRHSComponent ( OutputBuffer & OB ) const inline Definition at line 240 of file ItaniumDemangle.h . References hasRHSComponentSlow() , OutputBuffer , RHSComponentCache , Unknown , and Yes . ◆  hasRHSComponentSlow() virtual bool Node::hasRHSComponentSlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , PointerToMemberType , PointerType , QualType , and ReferenceType . Definition at line 265 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasRHSComponent() . ◆  print() void Node::print ( OutputBuffer & OB ) const inline Definition at line 286 of file ItaniumDemangle.h . References No , OutputBuffer , and RHSComponentCache . Referenced by llvm::ItaniumPartialDemangler::getFunctionDeclContextName() , llvm::DOTGraphTraits< AADepGraph * >::getNodeLabel() , llvm::DOTGraphTraits< const MachineFunction * >::getNodeLabel() , llvm::itaniumDemangle() , printAsOperand() , FoldExpr::printLeft() , and printNode() . ◆  printAsOperand() void Node::printAsOperand ( OutputBuffer & OB , Prec P = Prec::Default , bool StrictlyWorse = false  ) const inline Definition at line 275 of file ItaniumDemangle.h . References Default , getPrecedence() , OutputBuffer , P , and print() . Referenced by llvm::DOTGraphTraits< DOTFuncInfo * >::getBBName() , getSimpleNodeName() , llvm::operator<<() , llvm::VPIRMetadata::print() , and llvm::SimpleNodeLabelString() . ◆  printInitListAsType() virtual bool Node::printInitListAsType ( OutputBuffer & , const NodeArray &  ) const inline virtual Reimplemented in ArrayType . Definition at line 295 of file ItaniumDemangle.h . References OutputBuffer . ◆  visit() template<typename Fn> void Node::visit ( Fn F ) const Visit the most-derived object corresponding to this object. Visit the node. Calls F(P) , where P is the node cast to the appropriate derived class. Definition at line 2639 of file ItaniumDemangle.h . References DEMANGLE_ASSERT , and F . Friends And Related Symbol Documentation ◆  OutputBuffer friend class OutputBuffer friend Definition at line 309 of file ItaniumDemangle.h . References OutputBuffer . Referenced by ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , hasArray() , ArrayType::hasArraySlow() , ForwardTemplateReference::hasArraySlow() , hasArraySlow() , ParameterPack::hasArraySlow() , QualType::hasArraySlow() , hasFunction() , ForwardTemplateReference::hasFunctionSlow() , FunctionEncoding::hasFunctionSlow() , FunctionType::hasFunctionSlow() , hasFunctionSlow() , ParameterPack::hasFunctionSlow() , QualType::hasFunctionSlow() , hasRHSComponent() , ArrayType::hasRHSComponentSlow() , ForwardTemplateReference::hasRHSComponentSlow() , FunctionEncoding::hasRHSComponentSlow() , FunctionType::hasRHSComponentSlow() , hasRHSComponentSlow() , ParameterPack::hasRHSComponentSlow() , PointerToMemberType::hasRHSComponentSlow() , PointerType::hasRHSComponentSlow() , QualType::hasRHSComponentSlow() , ReferenceType::hasRHSComponentSlow() , OutputBuffer , print() , printAsOperand() , ClosureTypeName::printDeclarator() , ArrayType::printInitListAsType() , printInitListAsType() , AbiTagAttr::printLeft() , ArraySubscriptExpr::printLeft() , ArrayType::printLeft() , BinaryExpr::printLeft() , BinaryFPType::printLeft() , BitIntType::printLeft() , BoolExpr::printLeft() , BracedExpr::printLeft() , BracedRangeExpr::printLeft() , CallExpr::printLeft() , CastExpr::printLeft() , ClosureTypeName::printLeft() , ConditionalExpr::printLeft() , ConstrainedTypeTemplateParamDecl::printLeft() , ConversionExpr::printLeft() , ConversionOperatorType::printLeft() , CtorDtorName::printLeft() , CtorVtableSpecialName::printLeft() , DeleteExpr::printLeft() , DotSuffix::printLeft() , DtorName::printLeft() , DynamicExceptionSpec::printLeft() , ElaboratedTypeSpefType::printLeft() , EnableIfAttr::printLeft() , EnclosingExpr::printLeft() , EnumLiteral::printLeft() , ExplicitObjectParameter::printLeft() , ExprRequirement::printLeft() , FloatLiteralImpl< float >::printLeft() , FoldExpr::printLeft() , ForwardTemplateReference::printLeft() , FunctionEncoding::printLeft() , FunctionParam::printLeft() , FunctionType::printLeft() , GlobalQualifiedName::printLeft() , InitListExpr::printLeft() , IntegerLiteral::printLeft() , LambdaExpr::printLeft() , LiteralOperator::printLeft() , LocalName::printLeft() , MemberExpr::printLeft() , MemberLikeFriendName::printLeft() , ModuleEntity::printLeft() , ModuleName::printLeft() , NameType::printLeft() , NameWithTemplateArgs::printLeft() , NestedName::printLeft() , NestedRequirement::printLeft() , NewExpr::printLeft() , NodeArrayNode::printLeft() , NoexceptSpec::printLeft() , NonTypeTemplateParamDecl::printLeft() , ObjCProtoName::printLeft() , ParameterPack::printLeft() , ParameterPackExpansion::printLeft() , PixelVectorType::printLeft() , PointerToMemberConversionExpr::printLeft() , PointerToMemberType::printLeft() , PointerType::printLeft() , PostfixExpr::printLeft() , PostfixQualifiedType::printLeft() , PrefixExpr::printLeft() , QualifiedName::printLeft() , QualType::printLeft() , ReferenceType::printLeft() , RequiresExpr::printLeft() , SizeofParamPackExpr::printLeft() , SpecialName::printLeft() , SpecialSubstitution::printLeft() , StringLiteral::printLeft() , StructuredBindingName::printLeft() , SubobjectExpr::printLeft() , SyntheticTemplateParamName::printLeft() , TemplateArgs::printLeft() , TemplateArgumentPack::printLeft() , TemplateParamPackDecl::printLeft() , TemplateParamQualifiedArg::printLeft() , TemplateTemplateParamDecl::printLeft() , ThrowExpr::printLeft() , TransformedType::printLeft() , TypeRequirement::printLeft() , TypeTemplateParamDecl::printLeft() , UnnamedTypeName::printLeft() , VectorType::printLeft() , VendorExtQualType::printLeft() , QualType::printQuals() , ArrayType::printRight() , ConstrainedTypeTemplateParamDecl::printRight() , ForwardTemplateReference::printRight() , FunctionEncoding::printRight() , FunctionType::printRight() , NonTypeTemplateParamDecl::printRight() , ParameterPack::printRight() , PointerToMemberType::printRight() , PointerType::printRight() , QualType::printRight() , ReferenceType::printRight() , TemplateParamPackDecl::printRight() , TemplateTemplateParamDecl::printRight() , and TypeTemplateParamDecl::printRight() . Member Data Documentation ◆  ArrayCache Cache Node::ArrayCache protected Track if this node is a (possibly qualified) array type. This can affect how we format the output string. Definition at line 214 of file ItaniumDemangle.h . Referenced by getArrayCache() , hasArray() , Node() , and ParameterPack::ParameterPack() . ◆  FunctionCache Cache Node::FunctionCache protected Track if this node is a (possibly qualified) function type. This can affect how we format the output string. Definition at line 218 of file ItaniumDemangle.h . Referenced by getFunctionCache() , hasFunction() , Node() , and ParameterPack::ParameterPack() . ◆  RHSComponentCache Cache Node::RHSComponentCache protected Tracks if this node has a component on its right side, in which case we need to call printRight. Definition at line 210 of file ItaniumDemangle.h . Referenced by getRHSComponentCache() , hasRHSComponent() , Node() , ParameterPack::ParameterPack() , and print() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classPODSmallVector.html#a04bb8f0efe33c21c02aaa891d4c556f7 | LLVM: PODSmallVector< T, N > Class Template Reference LLVM  22.0.0git Public Member Functions | List of all members PODSmallVector< T, N > Class Template Reference #include " llvm/Demangle/ItaniumDemangle.h " Inheritance diagram for PODSmallVector< T, N >: This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead. [ legend ] Public Member Functions   PODSmallVector ()   PODSmallVector ( const PODSmallVector &)=delete PODSmallVector &  operator= ( const PODSmallVector &)=delete   PODSmallVector ( PODSmallVector &&Other) PODSmallVector &  operator= ( PODSmallVector &&Other) void  push_back ( const T &Elem) void  pop_back () void  shrinkToSize (size_t Index) T *  begin () T *  end () bool   empty () const size_t  size () const T &  back () T &  operator[] (size_t Index) void  clear ()   ~PODSmallVector () Detailed Description template<class T , size_t N> class PODSmallVector< T, N > Definition at line 41 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  PODSmallVector() [1/3] template<class T , size_t N> PODSmallVector < T , N > ::PODSmallVector ( ) inline Definition at line 77 of file ItaniumDemangle.h . ◆  PODSmallVector() [2/3] template<class T , size_t N> PODSmallVector < T , N > ::PODSmallVector ( const PODSmallVector < T , N > & ) delete ◆  PODSmallVector() [3/3] template<class T , size_t N> PODSmallVector < T , N > ::PODSmallVector ( PODSmallVector < T , N > && Other ) inline Definition at line 82 of file ItaniumDemangle.h . ◆  ~PODSmallVector() template<class T , size_t N> PODSmallVector < T , N >::~ PODSmallVector ( ) inline Definition at line 156 of file ItaniumDemangle.h . Member Function Documentation ◆  back() template<class T , size_t N> T & PODSmallVector < T , N >::back ( ) inline Definition at line 146 of file ItaniumDemangle.h . ◆  begin() template<class T , size_t N> T * PODSmallVector < T , N >::begin ( ) inline Definition at line 141 of file ItaniumDemangle.h . Referenced by PODSmallVector< Node *, 8 >::operator[]() . ◆  clear() template<class T , size_t N> void PODSmallVector < T , N >::clear ( ) inline Definition at line 154 of file ItaniumDemangle.h . ◆  empty() template<class T , size_t N> bool PODSmallVector < T , N >::empty ( ) const inline Definition at line 144 of file ItaniumDemangle.h . ◆  end() template<class T , size_t N> T * PODSmallVector < T , N >::end ( ) inline Definition at line 142 of file ItaniumDemangle.h . ◆  operator=() [1/2] template<class T , size_t N> PODSmallVector & PODSmallVector < T , N >::operator= ( const PODSmallVector < T , N > & ) delete ◆  operator=() [2/2] template<class T , size_t N> PODSmallVector & PODSmallVector < T , N >::operator= ( PODSmallVector < T , N > && Other ) inline Definition at line 96 of file ItaniumDemangle.h . ◆  operator[]() template<class T , size_t N> T & PODSmallVector < T , N >::operator[] ( size_t Index ) inline Definition at line 150 of file ItaniumDemangle.h . ◆  pop_back() template<class T , size_t N> void PODSmallVector < T , N >::pop_back ( ) inline Definition at line 131 of file ItaniumDemangle.h . ◆  push_back() template<class T , size_t N> void PODSmallVector < T , N >::push_back ( const T & Elem ) inline Definition at line 124 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseTemplateParamDecl() . ◆  shrinkToSize() template<class T , size_t N> void PODSmallVector < T , N >::shrinkToSize ( size_t Index ) inline Definition at line 136 of file ItaniumDemangle.h . ◆  size() template<class T , size_t N> size_t PODSmallVector < T , N >::size ( ) const inline Definition at line 145 of file ItaniumDemangle.h . Referenced by PODSmallVector< Node *, 8 >::operator[]() , PODSmallVector< Node *, 8 >::push_back() , and PODSmallVector< Node *, 8 >::shrinkToSize() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Numpy | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Scipy | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Fast-Fourier-Transform | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNode.html#a98a5ee11ba66a0c8982700aad1c4844b | LLVM: Node Class Reference LLVM  22.0.0git Public Types | Public Member Functions | Protected Attributes | Friends | List of all members Node Class Reference abstract #include " llvm/Demangle/ItaniumDemangle.h " Inherited by FloatLiteralImpl< float > , FloatLiteralImpl< double > , FloatLiteralImpl< long double > , AbiTagAttr , ArraySubscriptExpr , ArrayType , BinaryExpr , BinaryFPType , BitIntType , BoolExpr , BracedExpr , BracedRangeExpr , CallExpr , CastExpr , ClosureTypeName , ConditionalExpr , ConstrainedTypeTemplateParamDecl , ConversionExpr , ConversionOperatorType , CtorDtorName , CtorVtableSpecialName , DeleteExpr , DotSuffix , DtorName , DynamicExceptionSpec , ElaboratedTypeSpefType , EnableIfAttr , EnclosingExpr , EnumLiteral , ExpandedSpecialSubstitution , ExplicitObjectParameter , ExprRequirement , FloatLiteralImpl< Float > , FoldExpr , ForwardTemplateReference , FunctionEncoding , FunctionParam , FunctionType , GlobalQualifiedName , InitListExpr , IntegerLiteral , LambdaExpr , LiteralOperator , LocalName , MemberExpr , MemberLikeFriendName , ModuleEntity , ModuleName , NameType , NameWithTemplateArgs , NestedName , NestedRequirement , NewExpr , NodeArrayNode , NoexceptSpec , NonTypeTemplateParamDecl , ObjCProtoName , ParameterPack , ParameterPackExpansion , PixelVectorType , PointerToMemberConversionExpr , PointerToMemberType , PointerType , PostfixExpr , PostfixQualifiedType , PrefixExpr , QualType , QualifiedName , ReferenceType , RequiresExpr , SizeofParamPackExpr , SpecialName , StringLiteral , StructuredBindingName , SubobjectExpr , SyntheticTemplateParamName , TemplateArgs , TemplateArgumentPack , TemplateParamPackDecl , TemplateParamQualifiedArg , TemplateTemplateParamDecl , ThrowExpr , TransformedType , TypeRequirement , TypeTemplateParamDecl , UnnamedTypeName , VectorType , and VendorExtQualType . Public Types enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Public Member Functions   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Protected Attributes Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Friends class  OutputBuffer Detailed Description Definition at line 166 of file ItaniumDemangle.h . Member Enumeration Documentation ◆  Cache enum class Node::Cache : uint8_t strong Three-way bool to track a cached value. Unknown is possible if this node has an unexpanded parameter pack below it that may affect this cache. Enumerator Yes  No  Unknown  Definition at line 175 of file ItaniumDemangle.h . ◆  Kind enum Node::Kind : uint8_t Definition at line 168 of file ItaniumDemangle.h . ◆  Prec enum class Node::Prec : uint8_t strong Operator precedence for expression nodes. Used to determine required parens in expression emission. Enumerator Primary  Postfix  Unary  Cast  PtrMem  Multiplicative  Additive  Shift  Spaceship  Relational  Equality  And  Xor  Ior  AndIf  OrIf  Conditional  Assign  Comma  Default  Definition at line 179 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  Node() [1/2] Node::Node ( Kind K_ , Prec Precedence_ = Prec::Primary , Cache RHSComponentCache_ = Cache::No , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 221 of file ItaniumDemangle.h . References ArrayCache , FunctionCache , No , Primary , and RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , ArraySubscriptExpr::ArraySubscriptExpr() , ArrayType::ArrayType() , BinaryExpr::BinaryExpr() , BinaryFPType::BinaryFPType() , BitIntType::BitIntType() , BoolExpr::BoolExpr() , BracedExpr::BracedExpr() , BracedRangeExpr::BracedRangeExpr() , CallExpr::CallExpr() , CastExpr::CastExpr() , ClosureTypeName::ClosureTypeName() , ConditionalExpr::ConditionalExpr() , ConstrainedTypeTemplateParamDecl::ConstrainedTypeTemplateParamDecl() , ConversionExpr::ConversionExpr() , ConversionOperatorType::ConversionOperatorType() , CtorDtorName::CtorDtorName() , CtorVtableSpecialName::CtorVtableSpecialName() , DeleteExpr::DeleteExpr() , DotSuffix::DotSuffix() , DtorName::DtorName() , DynamicExceptionSpec::DynamicExceptionSpec() , ElaboratedTypeSpefType::ElaboratedTypeSpefType() , EnableIfAttr::EnableIfAttr() , EnclosingExpr::EnclosingExpr() , EnumLiteral::EnumLiteral() , ExpandedSpecialSubstitution::ExpandedSpecialSubstitution() , ExplicitObjectParameter::ExplicitObjectParameter() , ExprRequirement::ExprRequirement() , FloatLiteralImpl< float >::FloatLiteralImpl() , FoldExpr::FoldExpr() , ForwardTemplateReference::ForwardTemplateReference() , FunctionEncoding::FunctionEncoding() , FunctionParam::FunctionParam() , FunctionType::FunctionType() , TemplateParamQualifiedArg::getArg() , FunctionEncoding::getAttrs() , VectorType::getBaseType() , ParameterPackExpansion::getChild() , QualType::getChild() , VectorType::getDimension() , FunctionEncoding::getName() , PointerType::getPointee() , FunctionEncoding::getRequires() , FunctionEncoding::getReturnType() , ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , VendorExtQualType::getTA() , VendorExtQualType::getTy() , GlobalQualifiedName::GlobalQualifiedName() , InitListExpr::InitListExpr() , IntegerLiteral::IntegerLiteral() , LambdaExpr::LambdaExpr() , LiteralOperator::LiteralOperator() , LocalName::LocalName() , MemberExpr::MemberExpr() , MemberLikeFriendName::MemberLikeFriendName() , ModuleEntity::ModuleEntity() , ModuleName::ModuleName() , NameType::NameType() , NameWithTemplateArgs::NameWithTemplateArgs() , NestedName::NestedName() , NestedRequirement::NestedRequirement() , NewExpr::NewExpr() , Node() , NodeArrayNode::NodeArrayNode() , NoexceptSpec::NoexceptSpec() , NonTypeTemplateParamDecl::NonTypeTemplateParamDecl() , ObjCProtoName::ObjCProtoName() , ParameterPack::ParameterPack() , ParameterPackExpansion::ParameterPackExpansion() , PixelVectorType::PixelVectorType() , PointerToMemberConversionExpr::PointerToMemberConversionExpr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , PostfixExpr::PostfixExpr() , PostfixQualifiedType::PostfixQualifiedType() , PrefixExpr::PrefixExpr() , RequiresExpr::printLeft() , QualifiedName::QualifiedName() , QualType::QualType() , ReferenceType::ReferenceType() , RequiresExpr::RequiresExpr() , SizeofParamPackExpr::SizeofParamPackExpr() , SpecialName::SpecialName() , StringLiteral::StringLiteral() , StructuredBindingName::StructuredBindingName() , SubobjectExpr::SubobjectExpr() , SyntheticTemplateParamName::SyntheticTemplateParamName() , TemplateArgs::TemplateArgs() , TemplateArgumentPack::TemplateArgumentPack() , TemplateParamPackDecl::TemplateParamPackDecl() , TemplateParamQualifiedArg::TemplateParamQualifiedArg() , TemplateTemplateParamDecl::TemplateTemplateParamDecl() , ThrowExpr::ThrowExpr() , TransformedType::TransformedType() , TypeRequirement::TypeRequirement() , TypeTemplateParamDecl::TypeTemplateParamDecl() , UnnamedTypeName::UnnamedTypeName() , VectorType::VectorType() , and VendorExtQualType::VendorExtQualType() . ◆  Node() [2/2] Node::Node ( Kind K_ , Cache RHSComponentCache_ , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 226 of file ItaniumDemangle.h . References No , Node() , and Primary . ◆  ~Node() virtual Node::~Node ( ) virtual default Member Function Documentation ◆  dump() DEMANGLE_DUMP_METHOD void Node::dump ( ) const References DEMANGLE_DUMP_METHOD . Referenced by llvm::DAGTypeLegalizer::run() , and llvm::RISCVDAGToDAGISel::Select() . ◆  getArrayCache() Cache Node::getArrayCache ( ) const inline Definition at line 262 of file ItaniumDemangle.h . References ArrayCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getBaseName() virtual std::string_view Node::getBaseName ( ) const inline virtual Reimplemented in AbiTagAttr , ExpandedSpecialSubstitution , GlobalQualifiedName , MemberLikeFriendName , ModuleEntity , NameType , NameWithTemplateArgs , NestedName , QualifiedName , and SpecialSubstitution . Definition at line 299 of file ItaniumDemangle.h . ◆  getFunctionCache() Cache Node::getFunctionCache ( ) const inline Definition at line 263 of file ItaniumDemangle.h . References FunctionCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getKind() Kind Node::getKind ( ) const inline Definition at line 258 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseCtorDtorName() , AbstractManglingParser< Derived, Alloc >::parseNestedName() , AbstractManglingParser< Derived, Alloc >::parseTemplateArgs() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnscopedName() , NodeArray::printAsString() , and llvm::msgpack::Document::writeToBlob() . ◆  getPrecedence() Prec Node::getPrecedence ( ) const inline Definition at line 260 of file ItaniumDemangle.h . Referenced by ArraySubscriptExpr::match() , BinaryExpr::match() , CallExpr::match() , CastExpr::match() , ConditionalExpr::match() , ConversionExpr::match() , DeleteExpr::match() , EnclosingExpr::match() , MemberExpr::match() , NewExpr::match() , PointerToMemberConversionExpr::match() , PostfixExpr::match() , PrefixExpr::match() , printAsOperand() , ArraySubscriptExpr::printLeft() , BinaryExpr::printLeft() , ConditionalExpr::printLeft() , MemberExpr::printLeft() , PostfixExpr::printLeft() , and PrefixExpr::printLeft() . ◆  getRHSComponentCache() Cache Node::getRHSComponentCache ( ) const inline Definition at line 261 of file ItaniumDemangle.h . References RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , QualType::QualType() , and ReferenceType::ReferenceType() . ◆  getSyntaxNode() virtual const Node * Node::getSyntaxNode ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , and ParameterPack . Definition at line 271 of file ItaniumDemangle.h . References Node() , and OutputBuffer . ◆  hasArray() bool Node::hasArray ( OutputBuffer & OB ) const inline Definition at line 246 of file ItaniumDemangle.h . References ArrayCache , hasArraySlow() , OutputBuffer , Unknown , and Yes . ◆  hasArraySlow() virtual bool Node::hasArraySlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , ParameterPack , and QualType . Definition at line 266 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasArray() . ◆  hasFunction() bool Node::hasFunction ( OutputBuffer & OB ) const inline Definition at line 252 of file ItaniumDemangle.h . References FunctionCache , hasFunctionSlow() , OutputBuffer , Unknown , and Yes . ◆  hasFunctionSlow() virtual bool Node::hasFunctionSlow ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , and QualType . Definition at line 267 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasFunction() . ◆  hasRHSComponent() bool Node::hasRHSComponent ( OutputBuffer & OB ) const inline Definition at line 240 of file ItaniumDemangle.h . References hasRHSComponentSlow() , OutputBuffer , RHSComponentCache , Unknown , and Yes . ◆  hasRHSComponentSlow() virtual bool Node::hasRHSComponentSlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , PointerToMemberType , PointerType , QualType , and ReferenceType . Definition at line 265 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasRHSComponent() . ◆  print() void Node::print ( OutputBuffer & OB ) const inline Definition at line 286 of file ItaniumDemangle.h . References No , OutputBuffer , and RHSComponentCache . Referenced by llvm::ItaniumPartialDemangler::getFunctionDeclContextName() , llvm::DOTGraphTraits< AADepGraph * >::getNodeLabel() , llvm::DOTGraphTraits< const MachineFunction * >::getNodeLabel() , llvm::itaniumDemangle() , printAsOperand() , FoldExpr::printLeft() , and printNode() . ◆  printAsOperand() void Node::printAsOperand ( OutputBuffer & OB , Prec P = Prec::Default , bool StrictlyWorse = false  ) const inline Definition at line 275 of file ItaniumDemangle.h . References Default , getPrecedence() , OutputBuffer , P , and print() . Referenced by llvm::DOTGraphTraits< DOTFuncInfo * >::getBBName() , getSimpleNodeName() , llvm::operator<<() , llvm::VPIRMetadata::print() , and llvm::SimpleNodeLabelString() . ◆  printInitListAsType() virtual bool Node::printInitListAsType ( OutputBuffer & , const NodeArray &  ) const inline virtual Reimplemented in ArrayType . Definition at line 295 of file ItaniumDemangle.h . References OutputBuffer . ◆  visit() template<typename Fn> void Node::visit ( Fn F ) const Visit the most-derived object corresponding to this object. Visit the node. Calls F(P) , where P is the node cast to the appropriate derived class. Definition at line 2639 of file ItaniumDemangle.h . References DEMANGLE_ASSERT , and F . Friends And Related Symbol Documentation ◆  OutputBuffer friend class OutputBuffer friend Definition at line 309 of file ItaniumDemangle.h . References OutputBuffer . Referenced by ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , hasArray() , ArrayType::hasArraySlow() , ForwardTemplateReference::hasArraySlow() , hasArraySlow() , ParameterPack::hasArraySlow() , QualType::hasArraySlow() , hasFunction() , ForwardTemplateReference::hasFunctionSlow() , FunctionEncoding::hasFunctionSlow() , FunctionType::hasFunctionSlow() , hasFunctionSlow() , ParameterPack::hasFunctionSlow() , QualType::hasFunctionSlow() , hasRHSComponent() , ArrayType::hasRHSComponentSlow() , ForwardTemplateReference::hasRHSComponentSlow() , FunctionEncoding::hasRHSComponentSlow() , FunctionType::hasRHSComponentSlow() , hasRHSComponentSlow() , ParameterPack::hasRHSComponentSlow() , PointerToMemberType::hasRHSComponentSlow() , PointerType::hasRHSComponentSlow() , QualType::hasRHSComponentSlow() , ReferenceType::hasRHSComponentSlow() , OutputBuffer , print() , printAsOperand() , ClosureTypeName::printDeclarator() , ArrayType::printInitListAsType() , printInitListAsType() , AbiTagAttr::printLeft() , ArraySubscriptExpr::printLeft() , ArrayType::printLeft() , BinaryExpr::printLeft() , BinaryFPType::printLeft() , BitIntType::printLeft() , BoolExpr::printLeft() , BracedExpr::printLeft() , BracedRangeExpr::printLeft() , CallExpr::printLeft() , CastExpr::printLeft() , ClosureTypeName::printLeft() , ConditionalExpr::printLeft() , ConstrainedTypeTemplateParamDecl::printLeft() , ConversionExpr::printLeft() , ConversionOperatorType::printLeft() , CtorDtorName::printLeft() , CtorVtableSpecialName::printLeft() , DeleteExpr::printLeft() , DotSuffix::printLeft() , DtorName::printLeft() , DynamicExceptionSpec::printLeft() , ElaboratedTypeSpefType::printLeft() , EnableIfAttr::printLeft() , EnclosingExpr::printLeft() , EnumLiteral::printLeft() , ExplicitObjectParameter::printLeft() , ExprRequirement::printLeft() , FloatLiteralImpl< float >::printLeft() , FoldExpr::printLeft() , ForwardTemplateReference::printLeft() , FunctionEncoding::printLeft() , FunctionParam::printLeft() , FunctionType::printLeft() , GlobalQualifiedName::printLeft() , InitListExpr::printLeft() , IntegerLiteral::printLeft() , LambdaExpr::printLeft() , LiteralOperator::printLeft() , LocalName::printLeft() , MemberExpr::printLeft() , MemberLikeFriendName::printLeft() , ModuleEntity::printLeft() , ModuleName::printLeft() , NameType::printLeft() , NameWithTemplateArgs::printLeft() , NestedName::printLeft() , NestedRequirement::printLeft() , NewExpr::printLeft() , NodeArrayNode::printLeft() , NoexceptSpec::printLeft() , NonTypeTemplateParamDecl::printLeft() , ObjCProtoName::printLeft() , ParameterPack::printLeft() , ParameterPackExpansion::printLeft() , PixelVectorType::printLeft() , PointerToMemberConversionExpr::printLeft() , PointerToMemberType::printLeft() , PointerType::printLeft() , PostfixExpr::printLeft() , PostfixQualifiedType::printLeft() , PrefixExpr::printLeft() , QualifiedName::printLeft() , QualType::printLeft() , ReferenceType::printLeft() , RequiresExpr::printLeft() , SizeofParamPackExpr::printLeft() , SpecialName::printLeft() , SpecialSubstitution::printLeft() , StringLiteral::printLeft() , StructuredBindingName::printLeft() , SubobjectExpr::printLeft() , SyntheticTemplateParamName::printLeft() , TemplateArgs::printLeft() , TemplateArgumentPack::printLeft() , TemplateParamPackDecl::printLeft() , TemplateParamQualifiedArg::printLeft() , TemplateTemplateParamDecl::printLeft() , ThrowExpr::printLeft() , TransformedType::printLeft() , TypeRequirement::printLeft() , TypeTemplateParamDecl::printLeft() , UnnamedTypeName::printLeft() , VectorType::printLeft() , VendorExtQualType::printLeft() , QualType::printQuals() , ArrayType::printRight() , ConstrainedTypeTemplateParamDecl::printRight() , ForwardTemplateReference::printRight() , FunctionEncoding::printRight() , FunctionType::printRight() , NonTypeTemplateParamDecl::printRight() , ParameterPack::printRight() , PointerToMemberType::printRight() , PointerType::printRight() , QualType::printRight() , ReferenceType::printRight() , TemplateParamPackDecl::printRight() , TemplateTemplateParamDecl::printRight() , and TypeTemplateParamDecl::printRight() . Member Data Documentation ◆  ArrayCache Cache Node::ArrayCache protected Track if this node is a (possibly qualified) array type. This can affect how we format the output string. Definition at line 214 of file ItaniumDemangle.h . Referenced by getArrayCache() , hasArray() , Node() , and ParameterPack::ParameterPack() . ◆  FunctionCache Cache Node::FunctionCache protected Track if this node is a (possibly qualified) function type. This can affect how we format the output string. Definition at line 218 of file ItaniumDemangle.h . Referenced by getFunctionCache() , hasFunction() , Node() , and ParameterPack::ParameterPack() . ◆  RHSComponentCache Cache Node::RHSComponentCache protected Tracks if this node has a component on its right side, in which case we need to call printRight. Definition at line 210 of file ItaniumDemangle.h . Referenced by getRHSComponentCache() , hasRHSComponent() , Node() , ParameterPack::ParameterPack() , and print() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNode.html#a8f5be86d12160cc864438a6745515bd5 | LLVM: Node Class Reference LLVM  22.0.0git Public Types | Public Member Functions | Protected Attributes | Friends | List of all members Node Class Reference abstract #include " llvm/Demangle/ItaniumDemangle.h " Inherited by FloatLiteralImpl< float > , FloatLiteralImpl< double > , FloatLiteralImpl< long double > , AbiTagAttr , ArraySubscriptExpr , ArrayType , BinaryExpr , BinaryFPType , BitIntType , BoolExpr , BracedExpr , BracedRangeExpr , CallExpr , CastExpr , ClosureTypeName , ConditionalExpr , ConstrainedTypeTemplateParamDecl , ConversionExpr , ConversionOperatorType , CtorDtorName , CtorVtableSpecialName , DeleteExpr , DotSuffix , DtorName , DynamicExceptionSpec , ElaboratedTypeSpefType , EnableIfAttr , EnclosingExpr , EnumLiteral , ExpandedSpecialSubstitution , ExplicitObjectParameter , ExprRequirement , FloatLiteralImpl< Float > , FoldExpr , ForwardTemplateReference , FunctionEncoding , FunctionParam , FunctionType , GlobalQualifiedName , InitListExpr , IntegerLiteral , LambdaExpr , LiteralOperator , LocalName , MemberExpr , MemberLikeFriendName , ModuleEntity , ModuleName , NameType , NameWithTemplateArgs , NestedName , NestedRequirement , NewExpr , NodeArrayNode , NoexceptSpec , NonTypeTemplateParamDecl , ObjCProtoName , ParameterPack , ParameterPackExpansion , PixelVectorType , PointerToMemberConversionExpr , PointerToMemberType , PointerType , PostfixExpr , PostfixQualifiedType , PrefixExpr , QualType , QualifiedName , ReferenceType , RequiresExpr , SizeofParamPackExpr , SpecialName , StringLiteral , StructuredBindingName , SubobjectExpr , SyntheticTemplateParamName , TemplateArgs , TemplateArgumentPack , TemplateParamPackDecl , TemplateParamQualifiedArg , TemplateTemplateParamDecl , ThrowExpr , TransformedType , TypeRequirement , TypeTemplateParamDecl , UnnamedTypeName , VectorType , and VendorExtQualType . Public Types enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Public Member Functions   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Protected Attributes Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Friends class  OutputBuffer Detailed Description Definition at line 166 of file ItaniumDemangle.h . Member Enumeration Documentation ◆  Cache enum class Node::Cache : uint8_t strong Three-way bool to track a cached value. Unknown is possible if this node has an unexpanded parameter pack below it that may affect this cache. Enumerator Yes  No  Unknown  Definition at line 175 of file ItaniumDemangle.h . ◆  Kind enum Node::Kind : uint8_t Definition at line 168 of file ItaniumDemangle.h . ◆  Prec enum class Node::Prec : uint8_t strong Operator precedence for expression nodes. Used to determine required parens in expression emission. Enumerator Primary  Postfix  Unary  Cast  PtrMem  Multiplicative  Additive  Shift  Spaceship  Relational  Equality  And  Xor  Ior  AndIf  OrIf  Conditional  Assign  Comma  Default  Definition at line 179 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  Node() [1/2] Node::Node ( Kind K_ , Prec Precedence_ = Prec::Primary , Cache RHSComponentCache_ = Cache::No , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 221 of file ItaniumDemangle.h . References ArrayCache , FunctionCache , No , Primary , and RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , ArraySubscriptExpr::ArraySubscriptExpr() , ArrayType::ArrayType() , BinaryExpr::BinaryExpr() , BinaryFPType::BinaryFPType() , BitIntType::BitIntType() , BoolExpr::BoolExpr() , BracedExpr::BracedExpr() , BracedRangeExpr::BracedRangeExpr() , CallExpr::CallExpr() , CastExpr::CastExpr() , ClosureTypeName::ClosureTypeName() , ConditionalExpr::ConditionalExpr() , ConstrainedTypeTemplateParamDecl::ConstrainedTypeTemplateParamDecl() , ConversionExpr::ConversionExpr() , ConversionOperatorType::ConversionOperatorType() , CtorDtorName::CtorDtorName() , CtorVtableSpecialName::CtorVtableSpecialName() , DeleteExpr::DeleteExpr() , DotSuffix::DotSuffix() , DtorName::DtorName() , DynamicExceptionSpec::DynamicExceptionSpec() , ElaboratedTypeSpefType::ElaboratedTypeSpefType() , EnableIfAttr::EnableIfAttr() , EnclosingExpr::EnclosingExpr() , EnumLiteral::EnumLiteral() , ExpandedSpecialSubstitution::ExpandedSpecialSubstitution() , ExplicitObjectParameter::ExplicitObjectParameter() , ExprRequirement::ExprRequirement() , FloatLiteralImpl< float >::FloatLiteralImpl() , FoldExpr::FoldExpr() , ForwardTemplateReference::ForwardTemplateReference() , FunctionEncoding::FunctionEncoding() , FunctionParam::FunctionParam() , FunctionType::FunctionType() , TemplateParamQualifiedArg::getArg() , FunctionEncoding::getAttrs() , VectorType::getBaseType() , ParameterPackExpansion::getChild() , QualType::getChild() , VectorType::getDimension() , FunctionEncoding::getName() , PointerType::getPointee() , FunctionEncoding::getRequires() , FunctionEncoding::getReturnType() , ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , VendorExtQualType::getTA() , VendorExtQualType::getTy() , GlobalQualifiedName::GlobalQualifiedName() , InitListExpr::InitListExpr() , IntegerLiteral::IntegerLiteral() , LambdaExpr::LambdaExpr() , LiteralOperator::LiteralOperator() , LocalName::LocalName() , MemberExpr::MemberExpr() , MemberLikeFriendName::MemberLikeFriendName() , ModuleEntity::ModuleEntity() , ModuleName::ModuleName() , NameType::NameType() , NameWithTemplateArgs::NameWithTemplateArgs() , NestedName::NestedName() , NestedRequirement::NestedRequirement() , NewExpr::NewExpr() , Node() , NodeArrayNode::NodeArrayNode() , NoexceptSpec::NoexceptSpec() , NonTypeTemplateParamDecl::NonTypeTemplateParamDecl() , ObjCProtoName::ObjCProtoName() , ParameterPack::ParameterPack() , ParameterPackExpansion::ParameterPackExpansion() , PixelVectorType::PixelVectorType() , PointerToMemberConversionExpr::PointerToMemberConversionExpr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , PostfixExpr::PostfixExpr() , PostfixQualifiedType::PostfixQualifiedType() , PrefixExpr::PrefixExpr() , RequiresExpr::printLeft() , QualifiedName::QualifiedName() , QualType::QualType() , ReferenceType::ReferenceType() , RequiresExpr::RequiresExpr() , SizeofParamPackExpr::SizeofParamPackExpr() , SpecialName::SpecialName() , StringLiteral::StringLiteral() , StructuredBindingName::StructuredBindingName() , SubobjectExpr::SubobjectExpr() , SyntheticTemplateParamName::SyntheticTemplateParamName() , TemplateArgs::TemplateArgs() , TemplateArgumentPack::TemplateArgumentPack() , TemplateParamPackDecl::TemplateParamPackDecl() , TemplateParamQualifiedArg::TemplateParamQualifiedArg() , TemplateTemplateParamDecl::TemplateTemplateParamDecl() , ThrowExpr::ThrowExpr() , TransformedType::TransformedType() , TypeRequirement::TypeRequirement() , TypeTemplateParamDecl::TypeTemplateParamDecl() , UnnamedTypeName::UnnamedTypeName() , VectorType::VectorType() , and VendorExtQualType::VendorExtQualType() . ◆  Node() [2/2] Node::Node ( Kind K_ , Cache RHSComponentCache_ , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 226 of file ItaniumDemangle.h . References No , Node() , and Primary . ◆  ~Node() virtual Node::~Node ( ) virtual default Member Function Documentation ◆  dump() DEMANGLE_DUMP_METHOD void Node::dump ( ) const References DEMANGLE_DUMP_METHOD . Referenced by llvm::DAGTypeLegalizer::run() , and llvm::RISCVDAGToDAGISel::Select() . ◆  getArrayCache() Cache Node::getArrayCache ( ) const inline Definition at line 262 of file ItaniumDemangle.h . References ArrayCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getBaseName() virtual std::string_view Node::getBaseName ( ) const inline virtual Reimplemented in AbiTagAttr , ExpandedSpecialSubstitution , GlobalQualifiedName , MemberLikeFriendName , ModuleEntity , NameType , NameWithTemplateArgs , NestedName , QualifiedName , and SpecialSubstitution . Definition at line 299 of file ItaniumDemangle.h . ◆  getFunctionCache() Cache Node::getFunctionCache ( ) const inline Definition at line 263 of file ItaniumDemangle.h . References FunctionCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getKind() Kind Node::getKind ( ) const inline Definition at line 258 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseCtorDtorName() , AbstractManglingParser< Derived, Alloc >::parseNestedName() , AbstractManglingParser< Derived, Alloc >::parseTemplateArgs() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnscopedName() , NodeArray::printAsString() , and llvm::msgpack::Document::writeToBlob() . ◆  getPrecedence() Prec Node::getPrecedence ( ) const inline Definition at line 260 of file ItaniumDemangle.h . Referenced by ArraySubscriptExpr::match() , BinaryExpr::match() , CallExpr::match() , CastExpr::match() , ConditionalExpr::match() , ConversionExpr::match() , DeleteExpr::match() , EnclosingExpr::match() , MemberExpr::match() , NewExpr::match() , PointerToMemberConversionExpr::match() , PostfixExpr::match() , PrefixExpr::match() , printAsOperand() , ArraySubscriptExpr::printLeft() , BinaryExpr::printLeft() , ConditionalExpr::printLeft() , MemberExpr::printLeft() , PostfixExpr::printLeft() , and PrefixExpr::printLeft() . ◆  getRHSComponentCache() Cache Node::getRHSComponentCache ( ) const inline Definition at line 261 of file ItaniumDemangle.h . References RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , QualType::QualType() , and ReferenceType::ReferenceType() . ◆  getSyntaxNode() virtual const Node * Node::getSyntaxNode ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , and ParameterPack . Definition at line 271 of file ItaniumDemangle.h . References Node() , and OutputBuffer . ◆  hasArray() bool Node::hasArray ( OutputBuffer & OB ) const inline Definition at line 246 of file ItaniumDemangle.h . References ArrayCache , hasArraySlow() , OutputBuffer , Unknown , and Yes . ◆  hasArraySlow() virtual bool Node::hasArraySlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , ParameterPack , and QualType . Definition at line 266 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasArray() . ◆  hasFunction() bool Node::hasFunction ( OutputBuffer & OB ) const inline Definition at line 252 of file ItaniumDemangle.h . References FunctionCache , hasFunctionSlow() , OutputBuffer , Unknown , and Yes . ◆  hasFunctionSlow() virtual bool Node::hasFunctionSlow ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , and QualType . Definition at line 267 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasFunction() . ◆  hasRHSComponent() bool Node::hasRHSComponent ( OutputBuffer & OB ) const inline Definition at line 240 of file ItaniumDemangle.h . References hasRHSComponentSlow() , OutputBuffer , RHSComponentCache , Unknown , and Yes . ◆  hasRHSComponentSlow() virtual bool Node::hasRHSComponentSlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , PointerToMemberType , PointerType , QualType , and ReferenceType . Definition at line 265 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasRHSComponent() . ◆  print() void Node::print ( OutputBuffer & OB ) const inline Definition at line 286 of file ItaniumDemangle.h . References No , OutputBuffer , and RHSComponentCache . Referenced by llvm::ItaniumPartialDemangler::getFunctionDeclContextName() , llvm::DOTGraphTraits< AADepGraph * >::getNodeLabel() , llvm::DOTGraphTraits< const MachineFunction * >::getNodeLabel() , llvm::itaniumDemangle() , printAsOperand() , FoldExpr::printLeft() , and printNode() . ◆  printAsOperand() void Node::printAsOperand ( OutputBuffer & OB , Prec P = Prec::Default , bool StrictlyWorse = false  ) const inline Definition at line 275 of file ItaniumDemangle.h . References Default , getPrecedence() , OutputBuffer , P , and print() . Referenced by llvm::DOTGraphTraits< DOTFuncInfo * >::getBBName() , getSimpleNodeName() , llvm::operator<<() , llvm::VPIRMetadata::print() , and llvm::SimpleNodeLabelString() . ◆  printInitListAsType() virtual bool Node::printInitListAsType ( OutputBuffer & , const NodeArray &  ) const inline virtual Reimplemented in ArrayType . Definition at line 295 of file ItaniumDemangle.h . References OutputBuffer . ◆  visit() template<typename Fn> void Node::visit ( Fn F ) const Visit the most-derived object corresponding to this object. Visit the node. Calls F(P) , where P is the node cast to the appropriate derived class. Definition at line 2639 of file ItaniumDemangle.h . References DEMANGLE_ASSERT , and F . Friends And Related Symbol Documentation ◆  OutputBuffer friend class OutputBuffer friend Definition at line 309 of file ItaniumDemangle.h . References OutputBuffer . Referenced by ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , hasArray() , ArrayType::hasArraySlow() , ForwardTemplateReference::hasArraySlow() , hasArraySlow() , ParameterPack::hasArraySlow() , QualType::hasArraySlow() , hasFunction() , ForwardTemplateReference::hasFunctionSlow() , FunctionEncoding::hasFunctionSlow() , FunctionType::hasFunctionSlow() , hasFunctionSlow() , ParameterPack::hasFunctionSlow() , QualType::hasFunctionSlow() , hasRHSComponent() , ArrayType::hasRHSComponentSlow() , ForwardTemplateReference::hasRHSComponentSlow() , FunctionEncoding::hasRHSComponentSlow() , FunctionType::hasRHSComponentSlow() , hasRHSComponentSlow() , ParameterPack::hasRHSComponentSlow() , PointerToMemberType::hasRHSComponentSlow() , PointerType::hasRHSComponentSlow() , QualType::hasRHSComponentSlow() , ReferenceType::hasRHSComponentSlow() , OutputBuffer , print() , printAsOperand() , ClosureTypeName::printDeclarator() , ArrayType::printInitListAsType() , printInitListAsType() , AbiTagAttr::printLeft() , ArraySubscriptExpr::printLeft() , ArrayType::printLeft() , BinaryExpr::printLeft() , BinaryFPType::printLeft() , BitIntType::printLeft() , BoolExpr::printLeft() , BracedExpr::printLeft() , BracedRangeExpr::printLeft() , CallExpr::printLeft() , CastExpr::printLeft() , ClosureTypeName::printLeft() , ConditionalExpr::printLeft() , ConstrainedTypeTemplateParamDecl::printLeft() , ConversionExpr::printLeft() , ConversionOperatorType::printLeft() , CtorDtorName::printLeft() , CtorVtableSpecialName::printLeft() , DeleteExpr::printLeft() , DotSuffix::printLeft() , DtorName::printLeft() , DynamicExceptionSpec::printLeft() , ElaboratedTypeSpefType::printLeft() , EnableIfAttr::printLeft() , EnclosingExpr::printLeft() , EnumLiteral::printLeft() , ExplicitObjectParameter::printLeft() , ExprRequirement::printLeft() , FloatLiteralImpl< float >::printLeft() , FoldExpr::printLeft() , ForwardTemplateReference::printLeft() , FunctionEncoding::printLeft() , FunctionParam::printLeft() , FunctionType::printLeft() , GlobalQualifiedName::printLeft() , InitListExpr::printLeft() , IntegerLiteral::printLeft() , LambdaExpr::printLeft() , LiteralOperator::printLeft() , LocalName::printLeft() , MemberExpr::printLeft() , MemberLikeFriendName::printLeft() , ModuleEntity::printLeft() , ModuleName::printLeft() , NameType::printLeft() , NameWithTemplateArgs::printLeft() , NestedName::printLeft() , NestedRequirement::printLeft() , NewExpr::printLeft() , NodeArrayNode::printLeft() , NoexceptSpec::printLeft() , NonTypeTemplateParamDecl::printLeft() , ObjCProtoName::printLeft() , ParameterPack::printLeft() , ParameterPackExpansion::printLeft() , PixelVectorType::printLeft() , PointerToMemberConversionExpr::printLeft() , PointerToMemberType::printLeft() , PointerType::printLeft() , PostfixExpr::printLeft() , PostfixQualifiedType::printLeft() , PrefixExpr::printLeft() , QualifiedName::printLeft() , QualType::printLeft() , ReferenceType::printLeft() , RequiresExpr::printLeft() , SizeofParamPackExpr::printLeft() , SpecialName::printLeft() , SpecialSubstitution::printLeft() , StringLiteral::printLeft() , StructuredBindingName::printLeft() , SubobjectExpr::printLeft() , SyntheticTemplateParamName::printLeft() , TemplateArgs::printLeft() , TemplateArgumentPack::printLeft() , TemplateParamPackDecl::printLeft() , TemplateParamQualifiedArg::printLeft() , TemplateTemplateParamDecl::printLeft() , ThrowExpr::printLeft() , TransformedType::printLeft() , TypeRequirement::printLeft() , TypeTemplateParamDecl::printLeft() , UnnamedTypeName::printLeft() , VectorType::printLeft() , VendorExtQualType::printLeft() , QualType::printQuals() , ArrayType::printRight() , ConstrainedTypeTemplateParamDecl::printRight() , ForwardTemplateReference::printRight() , FunctionEncoding::printRight() , FunctionType::printRight() , NonTypeTemplateParamDecl::printRight() , ParameterPack::printRight() , PointerToMemberType::printRight() , PointerType::printRight() , QualType::printRight() , ReferenceType::printRight() , TemplateParamPackDecl::printRight() , TemplateTemplateParamDecl::printRight() , and TypeTemplateParamDecl::printRight() . Member Data Documentation ◆  ArrayCache Cache Node::ArrayCache protected Track if this node is a (possibly qualified) array type. This can affect how we format the output string. Definition at line 214 of file ItaniumDemangle.h . Referenced by getArrayCache() , hasArray() , Node() , and ParameterPack::ParameterPack() . ◆  FunctionCache Cache Node::FunctionCache protected Track if this node is a (possibly qualified) function type. This can affect how we format the output string. Definition at line 218 of file ItaniumDemangle.h . Referenced by getFunctionCache() , hasFunction() , Node() , and ParameterPack::ParameterPack() . ◆  RHSComponentCache Cache Node::RHSComponentCache protected Tracks if this node has a component on its right side, in which case we need to call printRight. Definition at line 210 of file ItaniumDemangle.h . Referenced by getRHSComponentCache() , hasRHSComponent() , Node() , ParameterPack::ParameterPack() , and print() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Saving | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNode.html#a99161e08d77c16cf82f335c314dce7a9 | LLVM: Node Class Reference LLVM  22.0.0git Public Types | Public Member Functions | Protected Attributes | Friends | List of all members Node Class Reference abstract #include " llvm/Demangle/ItaniumDemangle.h " Inherited by FloatLiteralImpl< float > , FloatLiteralImpl< double > , FloatLiteralImpl< long double > , AbiTagAttr , ArraySubscriptExpr , ArrayType , BinaryExpr , BinaryFPType , BitIntType , BoolExpr , BracedExpr , BracedRangeExpr , CallExpr , CastExpr , ClosureTypeName , ConditionalExpr , ConstrainedTypeTemplateParamDecl , ConversionExpr , ConversionOperatorType , CtorDtorName , CtorVtableSpecialName , DeleteExpr , DotSuffix , DtorName , DynamicExceptionSpec , ElaboratedTypeSpefType , EnableIfAttr , EnclosingExpr , EnumLiteral , ExpandedSpecialSubstitution , ExplicitObjectParameter , ExprRequirement , FloatLiteralImpl< Float > , FoldExpr , ForwardTemplateReference , FunctionEncoding , FunctionParam , FunctionType , GlobalQualifiedName , InitListExpr , IntegerLiteral , LambdaExpr , LiteralOperator , LocalName , MemberExpr , MemberLikeFriendName , ModuleEntity , ModuleName , NameType , NameWithTemplateArgs , NestedName , NestedRequirement , NewExpr , NodeArrayNode , NoexceptSpec , NonTypeTemplateParamDecl , ObjCProtoName , ParameterPack , ParameterPackExpansion , PixelVectorType , PointerToMemberConversionExpr , PointerToMemberType , PointerType , PostfixExpr , PostfixQualifiedType , PrefixExpr , QualType , QualifiedName , ReferenceType , RequiresExpr , SizeofParamPackExpr , SpecialName , StringLiteral , StructuredBindingName , SubobjectExpr , SyntheticTemplateParamName , TemplateArgs , TemplateArgumentPack , TemplateParamPackDecl , TemplateParamQualifiedArg , TemplateTemplateParamDecl , ThrowExpr , TransformedType , TypeRequirement , TypeTemplateParamDecl , UnnamedTypeName , VectorType , and VendorExtQualType . Public Types enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Public Member Functions   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Protected Attributes Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Friends class  OutputBuffer Detailed Description Definition at line 166 of file ItaniumDemangle.h . Member Enumeration Documentation ◆  Cache enum class Node::Cache : uint8_t strong Three-way bool to track a cached value. Unknown is possible if this node has an unexpanded parameter pack below it that may affect this cache. Enumerator Yes  No  Unknown  Definition at line 175 of file ItaniumDemangle.h . ◆  Kind enum Node::Kind : uint8_t Definition at line 168 of file ItaniumDemangle.h . ◆  Prec enum class Node::Prec : uint8_t strong Operator precedence for expression nodes. Used to determine required parens in expression emission. Enumerator Primary  Postfix  Unary  Cast  PtrMem  Multiplicative  Additive  Shift  Spaceship  Relational  Equality  And  Xor  Ior  AndIf  OrIf  Conditional  Assign  Comma  Default  Definition at line 179 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  Node() [1/2] Node::Node ( Kind K_ , Prec Precedence_ = Prec::Primary , Cache RHSComponentCache_ = Cache::No , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 221 of file ItaniumDemangle.h . References ArrayCache , FunctionCache , No , Primary , and RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , ArraySubscriptExpr::ArraySubscriptExpr() , ArrayType::ArrayType() , BinaryExpr::BinaryExpr() , BinaryFPType::BinaryFPType() , BitIntType::BitIntType() , BoolExpr::BoolExpr() , BracedExpr::BracedExpr() , BracedRangeExpr::BracedRangeExpr() , CallExpr::CallExpr() , CastExpr::CastExpr() , ClosureTypeName::ClosureTypeName() , ConditionalExpr::ConditionalExpr() , ConstrainedTypeTemplateParamDecl::ConstrainedTypeTemplateParamDecl() , ConversionExpr::ConversionExpr() , ConversionOperatorType::ConversionOperatorType() , CtorDtorName::CtorDtorName() , CtorVtableSpecialName::CtorVtableSpecialName() , DeleteExpr::DeleteExpr() , DotSuffix::DotSuffix() , DtorName::DtorName() , DynamicExceptionSpec::DynamicExceptionSpec() , ElaboratedTypeSpefType::ElaboratedTypeSpefType() , EnableIfAttr::EnableIfAttr() , EnclosingExpr::EnclosingExpr() , EnumLiteral::EnumLiteral() , ExpandedSpecialSubstitution::ExpandedSpecialSubstitution() , ExplicitObjectParameter::ExplicitObjectParameter() , ExprRequirement::ExprRequirement() , FloatLiteralImpl< float >::FloatLiteralImpl() , FoldExpr::FoldExpr() , ForwardTemplateReference::ForwardTemplateReference() , FunctionEncoding::FunctionEncoding() , FunctionParam::FunctionParam() , FunctionType::FunctionType() , TemplateParamQualifiedArg::getArg() , FunctionEncoding::getAttrs() , VectorType::getBaseType() , ParameterPackExpansion::getChild() , QualType::getChild() , VectorType::getDimension() , FunctionEncoding::getName() , PointerType::getPointee() , FunctionEncoding::getRequires() , FunctionEncoding::getReturnType() , ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , VendorExtQualType::getTA() , VendorExtQualType::getTy() , GlobalQualifiedName::GlobalQualifiedName() , InitListExpr::InitListExpr() , IntegerLiteral::IntegerLiteral() , LambdaExpr::LambdaExpr() , LiteralOperator::LiteralOperator() , LocalName::LocalName() , MemberExpr::MemberExpr() , MemberLikeFriendName::MemberLikeFriendName() , ModuleEntity::ModuleEntity() , ModuleName::ModuleName() , NameType::NameType() , NameWithTemplateArgs::NameWithTemplateArgs() , NestedName::NestedName() , NestedRequirement::NestedRequirement() , NewExpr::NewExpr() , Node() , NodeArrayNode::NodeArrayNode() , NoexceptSpec::NoexceptSpec() , NonTypeTemplateParamDecl::NonTypeTemplateParamDecl() , ObjCProtoName::ObjCProtoName() , ParameterPack::ParameterPack() , ParameterPackExpansion::ParameterPackExpansion() , PixelVectorType::PixelVectorType() , PointerToMemberConversionExpr::PointerToMemberConversionExpr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , PostfixExpr::PostfixExpr() , PostfixQualifiedType::PostfixQualifiedType() , PrefixExpr::PrefixExpr() , RequiresExpr::printLeft() , QualifiedName::QualifiedName() , QualType::QualType() , ReferenceType::ReferenceType() , RequiresExpr::RequiresExpr() , SizeofParamPackExpr::SizeofParamPackExpr() , SpecialName::SpecialName() , StringLiteral::StringLiteral() , StructuredBindingName::StructuredBindingName() , SubobjectExpr::SubobjectExpr() , SyntheticTemplateParamName::SyntheticTemplateParamName() , TemplateArgs::TemplateArgs() , TemplateArgumentPack::TemplateArgumentPack() , TemplateParamPackDecl::TemplateParamPackDecl() , TemplateParamQualifiedArg::TemplateParamQualifiedArg() , TemplateTemplateParamDecl::TemplateTemplateParamDecl() , ThrowExpr::ThrowExpr() , TransformedType::TransformedType() , TypeRequirement::TypeRequirement() , TypeTemplateParamDecl::TypeTemplateParamDecl() , UnnamedTypeName::UnnamedTypeName() , VectorType::VectorType() , and VendorExtQualType::VendorExtQualType() . ◆  Node() [2/2] Node::Node ( Kind K_ , Cache RHSComponentCache_ , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 226 of file ItaniumDemangle.h . References No , Node() , and Primary . ◆  ~Node() virtual Node::~Node ( ) virtual default Member Function Documentation ◆  dump() DEMANGLE_DUMP_METHOD void Node::dump ( ) const References DEMANGLE_DUMP_METHOD . Referenced by llvm::DAGTypeLegalizer::run() , and llvm::RISCVDAGToDAGISel::Select() . ◆  getArrayCache() Cache Node::getArrayCache ( ) const inline Definition at line 262 of file ItaniumDemangle.h . References ArrayCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getBaseName() virtual std::string_view Node::getBaseName ( ) const inline virtual Reimplemented in AbiTagAttr , ExpandedSpecialSubstitution , GlobalQualifiedName , MemberLikeFriendName , ModuleEntity , NameType , NameWithTemplateArgs , NestedName , QualifiedName , and SpecialSubstitution . Definition at line 299 of file ItaniumDemangle.h . ◆  getFunctionCache() Cache Node::getFunctionCache ( ) const inline Definition at line 263 of file ItaniumDemangle.h . References FunctionCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getKind() Kind Node::getKind ( ) const inline Definition at line 258 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseCtorDtorName() , AbstractManglingParser< Derived, Alloc >::parseNestedName() , AbstractManglingParser< Derived, Alloc >::parseTemplateArgs() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnscopedName() , NodeArray::printAsString() , and llvm::msgpack::Document::writeToBlob() . ◆  getPrecedence() Prec Node::getPrecedence ( ) const inline Definition at line 260 of file ItaniumDemangle.h . Referenced by ArraySubscriptExpr::match() , BinaryExpr::match() , CallExpr::match() , CastExpr::match() , ConditionalExpr::match() , ConversionExpr::match() , DeleteExpr::match() , EnclosingExpr::match() , MemberExpr::match() , NewExpr::match() , PointerToMemberConversionExpr::match() , PostfixExpr::match() , PrefixExpr::match() , printAsOperand() , ArraySubscriptExpr::printLeft() , BinaryExpr::printLeft() , ConditionalExpr::printLeft() , MemberExpr::printLeft() , PostfixExpr::printLeft() , and PrefixExpr::printLeft() . ◆  getRHSComponentCache() Cache Node::getRHSComponentCache ( ) const inline Definition at line 261 of file ItaniumDemangle.h . References RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , QualType::QualType() , and ReferenceType::ReferenceType() . ◆  getSyntaxNode() virtual const Node * Node::getSyntaxNode ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , and ParameterPack . Definition at line 271 of file ItaniumDemangle.h . References Node() , and OutputBuffer . ◆  hasArray() bool Node::hasArray ( OutputBuffer & OB ) const inline Definition at line 246 of file ItaniumDemangle.h . References ArrayCache , hasArraySlow() , OutputBuffer , Unknown , and Yes . ◆  hasArraySlow() virtual bool Node::hasArraySlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , ParameterPack , and QualType . Definition at line 266 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasArray() . ◆  hasFunction() bool Node::hasFunction ( OutputBuffer & OB ) const inline Definition at line 252 of file ItaniumDemangle.h . References FunctionCache , hasFunctionSlow() , OutputBuffer , Unknown , and Yes . ◆  hasFunctionSlow() virtual bool Node::hasFunctionSlow ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , and QualType . Definition at line 267 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasFunction() . ◆  hasRHSComponent() bool Node::hasRHSComponent ( OutputBuffer & OB ) const inline Definition at line 240 of file ItaniumDemangle.h . References hasRHSComponentSlow() , OutputBuffer , RHSComponentCache , Unknown , and Yes . ◆  hasRHSComponentSlow() virtual bool Node::hasRHSComponentSlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , PointerToMemberType , PointerType , QualType , and ReferenceType . Definition at line 265 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasRHSComponent() . ◆  print() void Node::print ( OutputBuffer & OB ) const inline Definition at line 286 of file ItaniumDemangle.h . References No , OutputBuffer , and RHSComponentCache . Referenced by llvm::ItaniumPartialDemangler::getFunctionDeclContextName() , llvm::DOTGraphTraits< AADepGraph * >::getNodeLabel() , llvm::DOTGraphTraits< const MachineFunction * >::getNodeLabel() , llvm::itaniumDemangle() , printAsOperand() , FoldExpr::printLeft() , and printNode() . ◆  printAsOperand() void Node::printAsOperand ( OutputBuffer & OB , Prec P = Prec::Default , bool StrictlyWorse = false  ) const inline Definition at line 275 of file ItaniumDemangle.h . References Default , getPrecedence() , OutputBuffer , P , and print() . Referenced by llvm::DOTGraphTraits< DOTFuncInfo * >::getBBName() , getSimpleNodeName() , llvm::operator<<() , llvm::VPIRMetadata::print() , and llvm::SimpleNodeLabelString() . ◆  printInitListAsType() virtual bool Node::printInitListAsType ( OutputBuffer & , const NodeArray &  ) const inline virtual Reimplemented in ArrayType . Definition at line 295 of file ItaniumDemangle.h . References OutputBuffer . ◆  visit() template<typename Fn> void Node::visit ( Fn F ) const Visit the most-derived object corresponding to this object. Visit the node. Calls F(P) , where P is the node cast to the appropriate derived class. Definition at line 2639 of file ItaniumDemangle.h . References DEMANGLE_ASSERT , and F . Friends And Related Symbol Documentation ◆  OutputBuffer friend class OutputBuffer friend Definition at line 309 of file ItaniumDemangle.h . References OutputBuffer . Referenced by ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , hasArray() , ArrayType::hasArraySlow() , ForwardTemplateReference::hasArraySlow() , hasArraySlow() , ParameterPack::hasArraySlow() , QualType::hasArraySlow() , hasFunction() , ForwardTemplateReference::hasFunctionSlow() , FunctionEncoding::hasFunctionSlow() , FunctionType::hasFunctionSlow() , hasFunctionSlow() , ParameterPack::hasFunctionSlow() , QualType::hasFunctionSlow() , hasRHSComponent() , ArrayType::hasRHSComponentSlow() , ForwardTemplateReference::hasRHSComponentSlow() , FunctionEncoding::hasRHSComponentSlow() , FunctionType::hasRHSComponentSlow() , hasRHSComponentSlow() , ParameterPack::hasRHSComponentSlow() , PointerToMemberType::hasRHSComponentSlow() , PointerType::hasRHSComponentSlow() , QualType::hasRHSComponentSlow() , ReferenceType::hasRHSComponentSlow() , OutputBuffer , print() , printAsOperand() , ClosureTypeName::printDeclarator() , ArrayType::printInitListAsType() , printInitListAsType() , AbiTagAttr::printLeft() , ArraySubscriptExpr::printLeft() , ArrayType::printLeft() , BinaryExpr::printLeft() , BinaryFPType::printLeft() , BitIntType::printLeft() , BoolExpr::printLeft() , BracedExpr::printLeft() , BracedRangeExpr::printLeft() , CallExpr::printLeft() , CastExpr::printLeft() , ClosureTypeName::printLeft() , ConditionalExpr::printLeft() , ConstrainedTypeTemplateParamDecl::printLeft() , ConversionExpr::printLeft() , ConversionOperatorType::printLeft() , CtorDtorName::printLeft() , CtorVtableSpecialName::printLeft() , DeleteExpr::printLeft() , DotSuffix::printLeft() , DtorName::printLeft() , DynamicExceptionSpec::printLeft() , ElaboratedTypeSpefType::printLeft() , EnableIfAttr::printLeft() , EnclosingExpr::printLeft() , EnumLiteral::printLeft() , ExplicitObjectParameter::printLeft() , ExprRequirement::printLeft() , FloatLiteralImpl< float >::printLeft() , FoldExpr::printLeft() , ForwardTemplateReference::printLeft() , FunctionEncoding::printLeft() , FunctionParam::printLeft() , FunctionType::printLeft() , GlobalQualifiedName::printLeft() , InitListExpr::printLeft() , IntegerLiteral::printLeft() , LambdaExpr::printLeft() , LiteralOperator::printLeft() , LocalName::printLeft() , MemberExpr::printLeft() , MemberLikeFriendName::printLeft() , ModuleEntity::printLeft() , ModuleName::printLeft() , NameType::printLeft() , NameWithTemplateArgs::printLeft() , NestedName::printLeft() , NestedRequirement::printLeft() , NewExpr::printLeft() , NodeArrayNode::printLeft() , NoexceptSpec::printLeft() , NonTypeTemplateParamDecl::printLeft() , ObjCProtoName::printLeft() , ParameterPack::printLeft() , ParameterPackExpansion::printLeft() , PixelVectorType::printLeft() , PointerToMemberConversionExpr::printLeft() , PointerToMemberType::printLeft() , PointerType::printLeft() , PostfixExpr::printLeft() , PostfixQualifiedType::printLeft() , PrefixExpr::printLeft() , QualifiedName::printLeft() , QualType::printLeft() , ReferenceType::printLeft() , RequiresExpr::printLeft() , SizeofParamPackExpr::printLeft() , SpecialName::printLeft() , SpecialSubstitution::printLeft() , StringLiteral::printLeft() , StructuredBindingName::printLeft() , SubobjectExpr::printLeft() , SyntheticTemplateParamName::printLeft() , TemplateArgs::printLeft() , TemplateArgumentPack::printLeft() , TemplateParamPackDecl::printLeft() , TemplateParamQualifiedArg::printLeft() , TemplateTemplateParamDecl::printLeft() , ThrowExpr::printLeft() , TransformedType::printLeft() , TypeRequirement::printLeft() , TypeTemplateParamDecl::printLeft() , UnnamedTypeName::printLeft() , VectorType::printLeft() , VendorExtQualType::printLeft() , QualType::printQuals() , ArrayType::printRight() , ConstrainedTypeTemplateParamDecl::printRight() , ForwardTemplateReference::printRight() , FunctionEncoding::printRight() , FunctionType::printRight() , NonTypeTemplateParamDecl::printRight() , ParameterPack::printRight() , PointerToMemberType::printRight() , PointerType::printRight() , QualType::printRight() , ReferenceType::printRight() , TemplateParamPackDecl::printRight() , TemplateTemplateParamDecl::printRight() , and TypeTemplateParamDecl::printRight() . Member Data Documentation ◆  ArrayCache Cache Node::ArrayCache protected Track if this node is a (possibly qualified) array type. This can affect how we format the output string. Definition at line 214 of file ItaniumDemangle.h . Referenced by getArrayCache() , hasArray() , Node() , and ParameterPack::ParameterPack() . ◆  FunctionCache Cache Node::FunctionCache protected Track if this node is a (possibly qualified) function type. This can affect how we format the output string. Definition at line 218 of file ItaniumDemangle.h . Referenced by getFunctionCache() , hasFunction() , Node() , and ParameterPack::ParameterPack() . ◆  RHSComponentCache Cache Node::RHSComponentCache protected Tracks if this node has a component on its right side, in which case we need to call printRight. Definition at line 210 of file ItaniumDemangle.h . Referenced by getRHSComponentCache() , hasRHSComponent() , Node() , ParameterPack::ParameterPack() , and print() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://www.timeforkids.com/k1/topics/history/ | TIME for Kids | History | Topic | K-1 Skip to main content Search Articles by Grade level Grades K-1 Articles Grade 2 Articles Grades 3-4 Articles Grades 5-6 Articles Topics Animals Arts Ask Angela Books Business Careers Community Culture Debate Earth Science Education Election 2024 Engineering Environment Food and Nutrition Games Government History Holidays Inventions Movies and Television Music and Theater Nature News People Places Podcasts Science Service Stars Space Sports The Human Body The View Transportation Weather World Young Game Changers Your $ Financial Literacy Content Grade 4 Edition Grade 5-6 Edition For Grown-ups Resource Spotlight Also from TIME for Kids: Log In role: none user_age: none editions: The page you are about to enter is for grown-ups. Enter your birth date to continue. Month (MM) 01 02 03 04 05 06 07 08 09 10 11 12 Year (YYYY) 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 Submit History United States Presidential Firsts December 20, 2023 There have been 46 U.S. presidents. Each has made a mark on the country’s history. But only a few can be called Number 1. George Washington was one of the country’s founders. He was the first president. He was elected… Audio United States Historic Firsts December 16, 2021 February is Black History Month. Here are some firsts in Black American history. Home Run! Jackie Robinson played baseball. He was the first famous Black player in the major leagues. He played for the Brooklyn Dodgers. That was in 1947.… Audio Spanish United States A Day for Veterans October 14, 2021 November 11 is an important day. It is called Veterans Day. A veteran is someone who was in the military. Veterans helped keep our country safe. This day honors their bravery. How the U.S. Celebrates A big ceremony is held… Audio United States United States Symbols April 22, 2021 A symbol is something that has a special meaning. One United States symbol is the flag. To Americans, the flag stands for freedom. Here are some other U.S. symbols. They remind us of the hopes our country is based on.… Audio Spanish World Changing Times November 29, 2019 Rome is an ancient city. It is in Italy. Sports were a big part of life in ancient Rome. Sports are still important to Romans. Compare how Romans watched sports in the past with how they watch them now. Ancient… Audio Spanish World Pieces of the Past November 29, 2019 What was life like in ancient Rome? In many ways, it was like our life today. Here are some objects that have survived. What do they tell you? People in ancient Rome played games. They used dice like these. These… Arts Amazing Artists December 27, 2018 Artists help us see our world differently. They inspire us. Read about four African-American artists. Who inspires you? Augusta Savage (1892–1962) Augusta Savage was a sculptor. She made figures out of clay and other materials. She was also a teacher.… World Travel Back in Time October 5, 2018 Welcome to Egypt. It is a country in North Africa. Read on to learn what life in Egypt was like more than 2,000 years ago. Pharaohs Kings and queens ruled ancient Egypt. They were called pharaohs. They made laws… Audio Spanish United States Meet Lady Liberty May 4, 2018 The Statue of Liberty is an American monument. She stands tall in New York Harbor. The statue was a gift from France in 1886. It was built in France. Then it was shipped across the ocean in pieces. Lady Liberty… Audio Spanish Contact us Privacy policy California privacy Terms of Service Subscribe CLASSROOM INTERNATIONAL © 2026 TIME USA, LLC. All Rights Reserved. Powered by WordPress.com VIP | 2026-01-13T09:30:39 |
https://code.videolan.org/videolan/skin-designer/-/commits/master | Commits · master · VideoLAN / skin-designer · GitLab Skip to content GitLab Explore Sign in Register Commits · master skin-designer Browse files Nov 27, 2019 Merge branch 'fix-build/macosx-dock/1' into 'master' · d97de16e Jean-Baptiste Kempf authored Nov 27, 2019 d97de16e Nov 26, 2019 main: fix build with macosx special hack · 29c04320 Alexandre Janniaux authored Nov 26, 2019 29c04320 main: remove trailing characters · 4071413b Alexandre Janniaux authored Nov 26, 2019 4071413b build.xml: upgrade to source/target 1.7 · 991f4788 Alexandre Janniaux authored Nov 26, 2019 991f4788 Apr 05, 2012 Added Basque translation by Xabier Aramendi · 98277e64 altglass authored Apr 05, 2012 98277e64 Mar 01, 2012 Added Hebrew translation by Yaron Shahrabani · b83beb00 altglass authored Mar 01, 2012 b83beb00 Nov 08, 2011 Added Estonian translation by Olav Mägi · 77365326 altglass authored Nov 08, 2011 77365326 Jun 05, 2011 Added Italian translation by Lorenzo Marrocchi · e15f25bb altglass authored Jun 05, 2011 e15f25bb Apr 02, 2011 Update Czech language file with correct UTF-8 encoding · d4d3bcf6 altglass authored Apr 02, 2011 d4d3bcf6 Mar 19, 2011 Added Czech translation by LoveCZabijak · dd97e552 altglass authored Mar 19, 2011 dd97e552 Added Czech translation by LoveCZabijak · d802c355 altglass authored Mar 19, 2011 d802c355 Mar 01, 2011 Update of Slovak translation by Marian Hikanik · 4889fe66 altglass authored Mar 01, 2011 4889fe66 Sep 12, 2010 add turkish translation by Kaya Zeren · 68c33505 altglass authored Sep 12, 2010 68c33505 Jul 03, 2010 +add Polish translation for WIN_IMAGE_ART (thanks to M.T.) · 13591260 altglass authored Jul 03, 2010 13591260 #fix: disallow " to appear in IDs, actions, and other values, so that skin... · 2ad36ad2 altglass authored Jul 03, 2010 2ad36ad2 Jul 02, 2010 +add run target to ANT script · 92d7b801 altglass authored Jul 02, 2010 92d7b801 May 16, 2010 complete french translation · c39d4908 altglass authored May 16, 2010 c39d4908 Feb 23, 2010 Bugfix: XML Output is now proper UTF-8 encoded if it contains special characters · 6eef3201 altglass authored Feb 23, 2010 6eef3201 +Serbian translation by Ђорђе Васиљевић · 9aee7a25 altglass authored Feb 23, 2010 9aee7a25 Jan 12, 2010 small change in Spanish translation · 6547364c altglass authored Jan 12, 2010 6547364c Jan 11, 2010 +Spanish translation · dde77c87 altglass authored Jan 11, 2010 dde77c87 Sep 30, 2009 Make the program usable on smaller screens, e.g. Netbooks · 4793a803 altglass authored Sep 30, 2009 4793a803 Sep 25, 2009 Polish translation by Michał Trzebiatowski. Fixed i/o to linux user home directory. · 9862e22f altglass authored Sep 25, 2009 9862e22f Sep 06, 2009 Added support for: vlc.isRecording, vlc.canRecord, vlc.nextFrame(), vlc.toggleRecord() · 8c4f8e0c altglass authored Sep 06, 2009 8c4f8e0c Aug 12, 2009 0.8.5 release · c092eb5b altglass authored Aug 12, 2009 c092eb5b Aug 09, 2009 Slider editing GUI: Added functionality to move control points · 90450143 altglass authored Aug 09, 2009 90450143 Jul 27, 2009 ProgressWindow centering fix · 26368141 altglass authored Jul 27, 2009 26368141 Jul 01, 2009 pt-br translation · ed62314f altglass authored Jul 01, 2009 ed62314f Jun 16, 2009 Forgot to commit those classes · f2b4a781 altglass authored Jun 16, 2009 f2b4a781 Remove deprecated API from resources · 923882ef altglass authored Jun 16, 2009 923882ef Updated translations · f58ace30 altglass authored Jun 16, 2009 f58ace30 Jun 15, 2009 language system fix · 15f7b3cd altglass authored Jun 15, 2009 15f7b3cd Jun 14, 2009 More slider editing work (far from finished) · 01ba03fd altglass authored Jun 14, 2009 01ba03fd Jun 12, 2009 Updated language files · 9987497f altglass authored Jun 12, 2009 9987497f update building HOWTO · ed7129a3 altglass authored Jun 12, 2009 ed7129a3 Korean translation. Thanks to airplanez · a9b9841a altglass authored Jun 12, 2009 a9b9841a Jun 11, 2009 Update version numbering for next release to 0.8.5 · 07b913c2 altglass authored Jun 11, 2009 07b913c2 Toolbar update, save toolbar position between sessions · 2dd8ca4b altglass authored Jun 11, 2009 2dd8ca4b Toolbar redesign using standard java classes · fe595b14 altglass authored Jun 11, 2009 fe595b14 New toolbar buttons, groundwork for slider edting · ba87a97a altglass authored Jun 11, 2009 ba87a97a Loading VideoLAN code repository instance | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Boolean-indexing | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://wiki.php.net/xfail_poll?do=index | PHP: Sitemap Login Register You are here: start › xfail_poll xfail_poll Sitemap This is a sitemap over all available pages ordered by namespaces . adopt-code-of-conduct doc gsoc ideas indication_of_interest internals issuetracker licenses notrfc p pear pecl php-gtk playground pplusplus qa release rfc summits systems sytems todo user usergroups vcs web wiki wiki.php.net canyouvote conferences corementorship cve doc email_etiquette_for_people_new_to_php_internals extensions-unmaintained gitstats_02_19 gitstats_09_17 gsoc ideas indication_of_interest internals issuetracker licenses pear pecl php-7.1-ideas php-gtk phpng-int phpng-upgrading phpng platforms playground qa redefine_constants_exception_strawpoll rfc-index rfc security_fixes security start summits svnmigration systems temporary_location_for_draft_documentation todo usergroups vcs voting web xfail_poll zts-improvement xfail_poll.txt · Last modified: 2025/04/03 13:08 by 127.0.0.1 Page Tools Show page Old revisions Backlinks Back to top Copyright © 2001-2026 The PHP Group Other PHP.net sites Privacy policy | 2026-01-13T09:30:39 |
https://safecode.org/our-work/ | Our Work - SAFECode Skip to content Search for: About Our Work Our Leadership Our History Press Principles Resource Centers Secure Development Practices Training and Culture Development Managing a Software Security Program Software Security for Buyers and Government Publications A-Z Training About SAFECode Training Training Program FAQ Login & Registration Profile Download Trainings Blog Membership Join SAFECode Our Members For Members Search for: Our Work Our Work Scott Licata 2024-04-02T16:22:10-04:00 Who We Are SAFECode is a global industry forum where business leaders and technical experts come together to exchange insights and ideas on creating, improving, and promoting scalable and effective software security programs. We believe that secure software development can only be achieved with an organizational commitment to the execution of a holistic assurance process, and that sharing information on that process and the practices it encompasses is the most effective way for software providers to help customers and other stakeholders manage software security risk. What We Do For Commercial Technology Providers SAFECode is one of the only places where business and technical leaders can safely and directly connect with other professionals tasked with managing highly scalable, global software security programs to exchange ideas, share lessons learned, and collaborate on ways to make a positive impact on both their businesses and the security of the greater technology ecosystem. SAFECode also offers a unique NDA-protected collaborative environment for software security managers to connect their team members with their industry peers to collaborate on technical challenges, guide SAFECode’s focus areas, and support their continued professional development. For Customers and Government Decision-makers There is no “secret sauce” for creating secure software. It is achieved through the successful execution of a holistic, scalable assurance process that should be transparent to those seeking to evaluate the security of the software they use. SAFECode provides information that helps customers and other stakeholders better understand how that process impacts the security of the software they purchase so that they can better manage supply chain risk. Software Developers and Application Security Professionals SAFECode’s membership is composed of some of the technology industry’s most recognized software security experts, as well as numerous security professionals and software engineers who focus on application and supply chain security every day. While these SAFECode members directly benefit from the knowledge-sharing opportunities presented by our unique, NDA-protected collaboration environment, we also strive to support the broader security community. As such, we freely share many of the artifacts of this expert collaboration including lessons they’ve learned, best practices they’ve found effective, and training and education initiatives they’ve used so that we can support the continued professional development of anyone interested in building more secure software. About Our Work Our Leadership Our History Press Principles Resource Centers Secure Development Practices Training and Culture Development Managing a Software Security Program Software Security for Buyers and Government Publications A-Z Training About SAFECode Training Training Program FAQ Login / Course Registration Learning Profile Blog Membership Become a Member Our Members Contact Us Copyright © 2007- Software Assurance Forum for Excellence in Code (SAFECode) – All Rights Reserved Privacy Policy X LinkedIn Page load link Go to Top | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classOutputBuffer.html#a4929740589c1d6555f06176074718906 | LLVM: OutputBuffer Class Reference LLVM  22.0.0git Public Member Functions | Public Attributes | List of all members OutputBuffer Class Reference #include " llvm/Demangle/Utility.h " Public Member Functions   OutputBuffer ( char *StartBuf, size_t Size )   OutputBuffer ( char *StartBuf, size_t *SizePtr)   OutputBuffer ()=default   OutputBuffer ( const OutputBuffer &)=delete OutputBuffer &  operator= ( const OutputBuffer &)=delete virtual  ~OutputBuffer ()=default   operator std::string_view () const virtual void  printLeft ( const Node & N )   Called by the demangler when printing the demangle tree. virtual void  printRight ( const Node & N ) virtual void  notifyInsertion (size_t, size_t)   Called when we write to this object anywhere other than the end. virtual void  notifyDeletion (size_t, size_t)   Called when we make the CurrentPosition of this object smaller. bool   isInParensInTemplateArgs () const   Returns true if we're currently between a '(' and ')' when printing template args. bool   isInsideTemplateArgs () const   Returns true if we're printing template args. void  printOpen ( char Open='(') void  printClose ( char Close=')') OutputBuffer &  operator+= (std::string_view R) OutputBuffer &  operator+= ( char C ) OutputBuffer &  prepend (std::string_view R) OutputBuffer &  operator<< (std::string_view R) OutputBuffer &  operator<< ( char C ) OutputBuffer &  operator<< (long long N ) OutputBuffer &  operator<< ( unsigned long long N ) OutputBuffer &  operator<< (long N ) OutputBuffer &  operator<< ( unsigned long N ) OutputBuffer &  operator<< (int N ) OutputBuffer &  operator<< ( unsigned int N ) void  insert (size_t Pos, const char *S, size_t N ) size_t  getCurrentPosition () const void  setCurrentPosition (size_t NewPos) char   back () const bool   empty () const char *  getBuffer () char *  getBufferEnd () size_t  getBufferCapacity () const Public Attributes unsigned   CurrentPackIndex = std::numeric_limits< unsigned >::max()   If a ParameterPackExpansion (or similar type) is encountered, the offset into the pack that we're currently printing. unsigned   CurrentPackMax = std::numeric_limits< unsigned >::max() struct {      unsigned     ParenDepth = 0    The depth of '(' and ')' inside the currently printed template arguments. More...     bool     InsideTemplate = false    True if we're currently printing a template argument. More... }  TemplateTracker Detailed Description Definition at line 34 of file Utility.h . Constructor & Destructor Documentation ◆  OutputBuffer() [1/4] OutputBuffer::OutputBuffer ( char * StartBuf , size_t Size  ) inline Definition at line 75 of file Utility.h . References Size . Referenced by operator+=() , operator+=() , operator<<() , operator<<() , operator<<() , operator<<() , operator<<() , operator<<() , operator<<() , operator<<() , operator=() , OutputBuffer() , OutputBuffer() , and prepend() . ◆  OutputBuffer() [2/4] OutputBuffer::OutputBuffer ( char * StartBuf , size_t * SizePtr  ) inline Definition at line 77 of file Utility.h . References OutputBuffer() . ◆  OutputBuffer() [3/4] OutputBuffer::OutputBuffer ( ) default ◆  OutputBuffer() [4/4] OutputBuffer::OutputBuffer ( const OutputBuffer & ) delete References OutputBuffer() . ◆  ~OutputBuffer() virtual OutputBuffer::~OutputBuffer ( ) virtual default Member Function Documentation ◆  back() char OutputBuffer::back ( ) const inline Definition at line 213 of file Utility.h . References DEMANGLE_ASSERT . ◆  empty() bool OutputBuffer::empty ( ) const inline Definition at line 218 of file Utility.h . ◆  getBuffer() char * OutputBuffer::getBuffer ( ) inline Definition at line 220 of file Utility.h . Referenced by llvm::dlangDemangle() , removeNullBytes() , and llvm::ThinLTOCodeGenerator::writeGeneratedObject() . ◆  getBufferCapacity() size_t OutputBuffer::getBufferCapacity ( ) const inline Definition at line 222 of file Utility.h . ◆  getBufferEnd() char * OutputBuffer::getBufferEnd ( ) inline Definition at line 221 of file Utility.h . ◆  getCurrentPosition() size_t OutputBuffer::getCurrentPosition ( ) const inline Definition at line 207 of file Utility.h . Referenced by decodePunycode() , llvm::dlangDemangle() , and removeNullBytes() . ◆  insert() void OutputBuffer::insert ( size_t Pos , const char * S , size_t N  ) inline Definition at line 194 of file Utility.h . References DEMANGLE_ASSERT , N , and notifyInsertion() . Referenced by decodePunycode() . ◆  isInParensInTemplateArgs() bool OutputBuffer::isInParensInTemplateArgs ( ) const inline Returns true if we're currently between a '(' and ')' when printing template args. Definition at line 118 of file Utility.h . References TemplateTracker . ◆  isInsideTemplateArgs() bool OutputBuffer::isInsideTemplateArgs ( ) const inline Returns true if we're printing template args. Definition at line 123 of file Utility.h . References TemplateTracker . Referenced by printClose() , and printOpen() . ◆  notifyDeletion() virtual void OutputBuffer::notifyDeletion ( size_t , size_t  ) inline virtual Called when we make the CurrentPosition of this object smaller. Definition at line 100 of file Utility.h . Referenced by setCurrentPosition() . ◆  notifyInsertion() virtual void OutputBuffer::notifyInsertion ( size_t , size_t  ) inline virtual Called when we write to this object anywhere other than the end. Definition at line 97 of file Utility.h . Referenced by insert() , and prepend() . ◆  operator std::string_view() OutputBuffer::operator std::string_view ( ) const inline Definition at line 86 of file Utility.h . ◆  operator+=() [1/2] OutputBuffer & OutputBuffer::operator+= ( char C ) inline Definition at line 145 of file Utility.h . References C() , and OutputBuffer() . ◆  operator+=() [2/2] OutputBuffer & OutputBuffer::operator+= ( std::string_view R ) inline Definition at line 136 of file Utility.h . References OutputBuffer() , and Size . ◆  operator<<() [1/8] OutputBuffer & OutputBuffer::operator<< ( char C ) inline Definition at line 168 of file Utility.h . References C() , and OutputBuffer() . ◆  operator<<() [2/8] OutputBuffer & OutputBuffer::operator<< ( int N ) inline Definition at line 186 of file Utility.h . References N , and OutputBuffer() . ◆  operator<<() [3/8] OutputBuffer & OutputBuffer::operator<< ( long long N ) inline Definition at line 170 of file Utility.h . References N , and OutputBuffer() . ◆  operator<<() [4/8] OutputBuffer & OutputBuffer::operator<< ( long N ) inline Definition at line 178 of file Utility.h . References N , and OutputBuffer() . ◆  operator<<() [5/8] OutputBuffer & OutputBuffer::operator<< ( std::string_view R ) inline Definition at line 166 of file Utility.h . References OutputBuffer() . ◆  operator<<() [6/8] OutputBuffer & OutputBuffer::operator<< ( unsigned int N ) inline Definition at line 190 of file Utility.h . References N , and OutputBuffer() . ◆  operator<<() [7/8] OutputBuffer & OutputBuffer::operator<< ( unsigned long long N ) inline Definition at line 174 of file Utility.h . References N , and OutputBuffer() . ◆  operator<<() [8/8] OutputBuffer & OutputBuffer::operator<< ( unsigned long N ) inline Definition at line 182 of file Utility.h . References N , and OutputBuffer() . ◆  operator=() OutputBuffer & OutputBuffer::operator= ( const OutputBuffer & ) delete References OutputBuffer() . ◆  prepend() OutputBuffer & OutputBuffer::prepend ( std::string_view R ) inline Definition at line 151 of file Utility.h . References notifyInsertion() , OutputBuffer() , and Size . ◆  printClose() void OutputBuffer::printClose ( char Close = ')' ) inline Definition at line 130 of file Utility.h . References isInsideTemplateArgs() , and TemplateTracker . ◆  printLeft() void OutputBuffer::printLeft ( const Node & N ) inline virtual Called by the demangler when printing the demangle tree. By default calls into Node::print {Left|Right} but can be overriden by clients to track additional state when printing the demangled name. Definition at line 6202 of file ItaniumDemangle.h . References N . ◆  printOpen() void OutputBuffer::printOpen ( char Open = '(' ) inline Definition at line 125 of file Utility.h . References isInsideTemplateArgs() , and TemplateTracker . ◆  printRight() void OutputBuffer::printRight ( const Node & N ) inline virtual Definition at line 6204 of file ItaniumDemangle.h . References N . ◆  setCurrentPosition() void OutputBuffer::setCurrentPosition ( size_t NewPos ) inline Definition at line 208 of file Utility.h . References notifyDeletion() . Referenced by llvm::dlangDemangle() , and removeNullBytes() . Member Data Documentation ◆  CurrentPackIndex unsigned OutputBuffer::CurrentPackIndex = std::numeric_limits< unsigned >::max() If a ParameterPackExpansion (or similar type) is encountered, the offset into the pack that we're currently printing. Definition at line 104 of file Utility.h . ◆  CurrentPackMax unsigned OutputBuffer::CurrentPackMax = std::numeric_limits< unsigned >::max() Definition at line 105 of file Utility.h . ◆  InsideTemplate bool OutputBuffer::InsideTemplate = false True if we're currently printing a template argument. Definition at line 113 of file Utility.h . ◆  ParenDepth unsigned OutputBuffer::ParenDepth = 0 The depth of '(' and ')' inside the currently printed template arguments. Definition at line 110 of file Utility.h . ◆  [struct] struct { ... } OutputBuffer::TemplateTracker Referenced by isInParensInTemplateArgs() , isInsideTemplateArgs() , printClose() , and printOpen() . The documentation for this class was generated from the following files: include/llvm/Demangle/ Utility.h include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Statistics | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://www.php.net/manual/uk/function.tidy-warning-count.php | PHP: tidy_warning_count - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box Tokenizer » « tidy_get_output Посібник з PHP Довідник функцій Інші базові розширення Tidy Tidy Функції Change language: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other tidy_warning_count (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document Опис tidy_warning_count ( tidy $tidy ): int Returns the number of Tidy warnings encountered for the specified document. Параметри tidy Об'єкт Tidy . Значення, що повертаються Returns the number of warnings. Приклади Приклад #1 tidy_warning_count() example <?php $html = '<p>test</i> <bogustag>bogus</bogustag>' ; $tidy = tidy_parse_string ( $html ); echo tidy_error_count ( $tidy ) . "\n" ; //1 echo tidy_warning_count ( $tidy ) . "\n" ; //5 ?> Прогляньте також tidy_error_count() - Returns the Number of Tidy errors encountered for specified document tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document Found A Problem? Learn How To Improve This Page • Submit a Pull Request • Report a Bug + add a note User Contributed Notes There are no user contributed notes for this page. Tidy Функції ob_​tidyhandler tidy_​access_​count tidy_​config_​count tidy_​error_​count tidy_​get_​output tidy_​warning_​count Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#shape-and-dtype | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/structNestedName.html#pub-attribs | LLVM: NestedName Struct Reference LLVM  22.0.0git Public Member Functions | Public Attributes | List of all members NestedName Struct Reference #include " llvm/Demangle/ItaniumDemangle.h " Inheritance diagram for NestedName: This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead. [ legend ] Public Member Functions   NestedName ( Node *Qual_, Node *Name_) template<typename Fn> void  match (Fn F ) const std::string_view  getBaseName () const override void  printLeft ( OutputBuffer &OB) const override Public Member Functions inherited from Node   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Public Attributes Node *  Qual Node *  Name Additional Inherited Members Public Types inherited from Node enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Protected Attributes inherited from Node Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Detailed Description Definition at line 1077 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  NestedName() NestedName::NestedName ( Node * Qual_ , Node * Name_  ) inline Definition at line 1081 of file ItaniumDemangle.h . References Name , Node::Node() , and Qual . Member Function Documentation ◆  getBaseName() std::string_view NestedName::getBaseName ( ) const inline override virtual Reimplemented from Node . Definition at line 1086 of file ItaniumDemangle.h . References Name . ◆  match() template<typename Fn> void NestedName::match ( Fn F ) const inline Definition at line 1084 of file ItaniumDemangle.h . References F , Name , and Qual . ◆  printLeft() void NestedName::printLeft ( OutputBuffer & OB ) const inline override virtual Implements Node . Definition at line 1088 of file ItaniumDemangle.h . References Name , Node::OutputBuffer , and Qual . Member Data Documentation ◆  Name Node * NestedName::Name Definition at line 1079 of file ItaniumDemangle.h . Referenced by getBaseName() , match() , NestedName() , and printLeft() . ◆  Qual Node * NestedName::Qual Definition at line 1078 of file ItaniumDemangle.h . Referenced by match() , NestedName() , and printLeft() . The documentation for this struct was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Visualizing-arrays | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Finer-figure-control | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#A-few-useful-functions | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Data-types | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://fr-fr.facebook.com/recover/initiate/?privacy_mutation_token=eyJ0eXBlIjo1LCJjcmVhdGlvbl90aW1lIjoxNzY4Mjk2MjU0fQ%3D%3D&ars=facebook_login&next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT0TfXpKf-syTcRfZolaYSaZxd_c23OvPxsy26GA871uv_piXdJIM2RfwgXPq7rGSj6VCJKPY9O1rAwDRUtyOkqa-ut1fiYPLYbXwO7EHolry1leWvNJK9F2PIqHcOo1x-XIlrCvBoDLSsj_ | Facebook Cette fonction est temporairement bloquée Cette fonction est temporairement bloquée Il semble que vous ayez abusé de cette fonctionnalité en l’utilisant trop vite. Vous n’êtes plus autorisé à l’utiliser. Back | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNode.html#a2d1960b858db5aa56ab73551f52d293b | LLVM: Node Class Reference LLVM  22.0.0git Public Types | Public Member Functions | Protected Attributes | Friends | List of all members Node Class Reference abstract #include " llvm/Demangle/ItaniumDemangle.h " Inherited by FloatLiteralImpl< float > , FloatLiteralImpl< double > , FloatLiteralImpl< long double > , AbiTagAttr , ArraySubscriptExpr , ArrayType , BinaryExpr , BinaryFPType , BitIntType , BoolExpr , BracedExpr , BracedRangeExpr , CallExpr , CastExpr , ClosureTypeName , ConditionalExpr , ConstrainedTypeTemplateParamDecl , ConversionExpr , ConversionOperatorType , CtorDtorName , CtorVtableSpecialName , DeleteExpr , DotSuffix , DtorName , DynamicExceptionSpec , ElaboratedTypeSpefType , EnableIfAttr , EnclosingExpr , EnumLiteral , ExpandedSpecialSubstitution , ExplicitObjectParameter , ExprRequirement , FloatLiteralImpl< Float > , FoldExpr , ForwardTemplateReference , FunctionEncoding , FunctionParam , FunctionType , GlobalQualifiedName , InitListExpr , IntegerLiteral , LambdaExpr , LiteralOperator , LocalName , MemberExpr , MemberLikeFriendName , ModuleEntity , ModuleName , NameType , NameWithTemplateArgs , NestedName , NestedRequirement , NewExpr , NodeArrayNode , NoexceptSpec , NonTypeTemplateParamDecl , ObjCProtoName , ParameterPack , ParameterPackExpansion , PixelVectorType , PointerToMemberConversionExpr , PointerToMemberType , PointerType , PostfixExpr , PostfixQualifiedType , PrefixExpr , QualType , QualifiedName , ReferenceType , RequiresExpr , SizeofParamPackExpr , SpecialName , StringLiteral , StructuredBindingName , SubobjectExpr , SyntheticTemplateParamName , TemplateArgs , TemplateArgumentPack , TemplateParamPackDecl , TemplateParamQualifiedArg , TemplateTemplateParamDecl , ThrowExpr , TransformedType , TypeRequirement , TypeTemplateParamDecl , UnnamedTypeName , VectorType , and VendorExtQualType . Public Types enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Public Member Functions   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Protected Attributes Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Friends class  OutputBuffer Detailed Description Definition at line 166 of file ItaniumDemangle.h . Member Enumeration Documentation ◆  Cache enum class Node::Cache : uint8_t strong Three-way bool to track a cached value. Unknown is possible if this node has an unexpanded parameter pack below it that may affect this cache. Enumerator Yes  No  Unknown  Definition at line 175 of file ItaniumDemangle.h . ◆  Kind enum Node::Kind : uint8_t Definition at line 168 of file ItaniumDemangle.h . ◆  Prec enum class Node::Prec : uint8_t strong Operator precedence for expression nodes. Used to determine required parens in expression emission. Enumerator Primary  Postfix  Unary  Cast  PtrMem  Multiplicative  Additive  Shift  Spaceship  Relational  Equality  And  Xor  Ior  AndIf  OrIf  Conditional  Assign  Comma  Default  Definition at line 179 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  Node() [1/2] Node::Node ( Kind K_ , Prec Precedence_ = Prec::Primary , Cache RHSComponentCache_ = Cache::No , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 221 of file ItaniumDemangle.h . References ArrayCache , FunctionCache , No , Primary , and RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , ArraySubscriptExpr::ArraySubscriptExpr() , ArrayType::ArrayType() , BinaryExpr::BinaryExpr() , BinaryFPType::BinaryFPType() , BitIntType::BitIntType() , BoolExpr::BoolExpr() , BracedExpr::BracedExpr() , BracedRangeExpr::BracedRangeExpr() , CallExpr::CallExpr() , CastExpr::CastExpr() , ClosureTypeName::ClosureTypeName() , ConditionalExpr::ConditionalExpr() , ConstrainedTypeTemplateParamDecl::ConstrainedTypeTemplateParamDecl() , ConversionExpr::ConversionExpr() , ConversionOperatorType::ConversionOperatorType() , CtorDtorName::CtorDtorName() , CtorVtableSpecialName::CtorVtableSpecialName() , DeleteExpr::DeleteExpr() , DotSuffix::DotSuffix() , DtorName::DtorName() , DynamicExceptionSpec::DynamicExceptionSpec() , ElaboratedTypeSpefType::ElaboratedTypeSpefType() , EnableIfAttr::EnableIfAttr() , EnclosingExpr::EnclosingExpr() , EnumLiteral::EnumLiteral() , ExpandedSpecialSubstitution::ExpandedSpecialSubstitution() , ExplicitObjectParameter::ExplicitObjectParameter() , ExprRequirement::ExprRequirement() , FloatLiteralImpl< float >::FloatLiteralImpl() , FoldExpr::FoldExpr() , ForwardTemplateReference::ForwardTemplateReference() , FunctionEncoding::FunctionEncoding() , FunctionParam::FunctionParam() , FunctionType::FunctionType() , TemplateParamQualifiedArg::getArg() , FunctionEncoding::getAttrs() , VectorType::getBaseType() , ParameterPackExpansion::getChild() , QualType::getChild() , VectorType::getDimension() , FunctionEncoding::getName() , PointerType::getPointee() , FunctionEncoding::getRequires() , FunctionEncoding::getReturnType() , ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , VendorExtQualType::getTA() , VendorExtQualType::getTy() , GlobalQualifiedName::GlobalQualifiedName() , InitListExpr::InitListExpr() , IntegerLiteral::IntegerLiteral() , LambdaExpr::LambdaExpr() , LiteralOperator::LiteralOperator() , LocalName::LocalName() , MemberExpr::MemberExpr() , MemberLikeFriendName::MemberLikeFriendName() , ModuleEntity::ModuleEntity() , ModuleName::ModuleName() , NameType::NameType() , NameWithTemplateArgs::NameWithTemplateArgs() , NestedName::NestedName() , NestedRequirement::NestedRequirement() , NewExpr::NewExpr() , Node() , NodeArrayNode::NodeArrayNode() , NoexceptSpec::NoexceptSpec() , NonTypeTemplateParamDecl::NonTypeTemplateParamDecl() , ObjCProtoName::ObjCProtoName() , ParameterPack::ParameterPack() , ParameterPackExpansion::ParameterPackExpansion() , PixelVectorType::PixelVectorType() , PointerToMemberConversionExpr::PointerToMemberConversionExpr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , PostfixExpr::PostfixExpr() , PostfixQualifiedType::PostfixQualifiedType() , PrefixExpr::PrefixExpr() , RequiresExpr::printLeft() , QualifiedName::QualifiedName() , QualType::QualType() , ReferenceType::ReferenceType() , RequiresExpr::RequiresExpr() , SizeofParamPackExpr::SizeofParamPackExpr() , SpecialName::SpecialName() , StringLiteral::StringLiteral() , StructuredBindingName::StructuredBindingName() , SubobjectExpr::SubobjectExpr() , SyntheticTemplateParamName::SyntheticTemplateParamName() , TemplateArgs::TemplateArgs() , TemplateArgumentPack::TemplateArgumentPack() , TemplateParamPackDecl::TemplateParamPackDecl() , TemplateParamQualifiedArg::TemplateParamQualifiedArg() , TemplateTemplateParamDecl::TemplateTemplateParamDecl() , ThrowExpr::ThrowExpr() , TransformedType::TransformedType() , TypeRequirement::TypeRequirement() , TypeTemplateParamDecl::TypeTemplateParamDecl() , UnnamedTypeName::UnnamedTypeName() , VectorType::VectorType() , and VendorExtQualType::VendorExtQualType() . ◆  Node() [2/2] Node::Node ( Kind K_ , Cache RHSComponentCache_ , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 226 of file ItaniumDemangle.h . References No , Node() , and Primary . ◆  ~Node() virtual Node::~Node ( ) virtual default Member Function Documentation ◆  dump() DEMANGLE_DUMP_METHOD void Node::dump ( ) const References DEMANGLE_DUMP_METHOD . Referenced by llvm::DAGTypeLegalizer::run() , and llvm::RISCVDAGToDAGISel::Select() . ◆  getArrayCache() Cache Node::getArrayCache ( ) const inline Definition at line 262 of file ItaniumDemangle.h . References ArrayCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getBaseName() virtual std::string_view Node::getBaseName ( ) const inline virtual Reimplemented in AbiTagAttr , ExpandedSpecialSubstitution , GlobalQualifiedName , MemberLikeFriendName , ModuleEntity , NameType , NameWithTemplateArgs , NestedName , QualifiedName , and SpecialSubstitution . Definition at line 299 of file ItaniumDemangle.h . ◆  getFunctionCache() Cache Node::getFunctionCache ( ) const inline Definition at line 263 of file ItaniumDemangle.h . References FunctionCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getKind() Kind Node::getKind ( ) const inline Definition at line 258 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseCtorDtorName() , AbstractManglingParser< Derived, Alloc >::parseNestedName() , AbstractManglingParser< Derived, Alloc >::parseTemplateArgs() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnscopedName() , NodeArray::printAsString() , and llvm::msgpack::Document::writeToBlob() . ◆  getPrecedence() Prec Node::getPrecedence ( ) const inline Definition at line 260 of file ItaniumDemangle.h . Referenced by ArraySubscriptExpr::match() , BinaryExpr::match() , CallExpr::match() , CastExpr::match() , ConditionalExpr::match() , ConversionExpr::match() , DeleteExpr::match() , EnclosingExpr::match() , MemberExpr::match() , NewExpr::match() , PointerToMemberConversionExpr::match() , PostfixExpr::match() , PrefixExpr::match() , printAsOperand() , ArraySubscriptExpr::printLeft() , BinaryExpr::printLeft() , ConditionalExpr::printLeft() , MemberExpr::printLeft() , PostfixExpr::printLeft() , and PrefixExpr::printLeft() . ◆  getRHSComponentCache() Cache Node::getRHSComponentCache ( ) const inline Definition at line 261 of file ItaniumDemangle.h . References RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , QualType::QualType() , and ReferenceType::ReferenceType() . ◆  getSyntaxNode() virtual const Node * Node::getSyntaxNode ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , and ParameterPack . Definition at line 271 of file ItaniumDemangle.h . References Node() , and OutputBuffer . ◆  hasArray() bool Node::hasArray ( OutputBuffer & OB ) const inline Definition at line 246 of file ItaniumDemangle.h . References ArrayCache , hasArraySlow() , OutputBuffer , Unknown , and Yes . ◆  hasArraySlow() virtual bool Node::hasArraySlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , ParameterPack , and QualType . Definition at line 266 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasArray() . ◆  hasFunction() bool Node::hasFunction ( OutputBuffer & OB ) const inline Definition at line 252 of file ItaniumDemangle.h . References FunctionCache , hasFunctionSlow() , OutputBuffer , Unknown , and Yes . ◆  hasFunctionSlow() virtual bool Node::hasFunctionSlow ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , and QualType . Definition at line 267 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasFunction() . ◆  hasRHSComponent() bool Node::hasRHSComponent ( OutputBuffer & OB ) const inline Definition at line 240 of file ItaniumDemangle.h . References hasRHSComponentSlow() , OutputBuffer , RHSComponentCache , Unknown , and Yes . ◆  hasRHSComponentSlow() virtual bool Node::hasRHSComponentSlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , PointerToMemberType , PointerType , QualType , and ReferenceType . Definition at line 265 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasRHSComponent() . ◆  print() void Node::print ( OutputBuffer & OB ) const inline Definition at line 286 of file ItaniumDemangle.h . References No , OutputBuffer , and RHSComponentCache . Referenced by llvm::ItaniumPartialDemangler::getFunctionDeclContextName() , llvm::DOTGraphTraits< AADepGraph * >::getNodeLabel() , llvm::DOTGraphTraits< const MachineFunction * >::getNodeLabel() , llvm::itaniumDemangle() , printAsOperand() , FoldExpr::printLeft() , and printNode() . ◆  printAsOperand() void Node::printAsOperand ( OutputBuffer & OB , Prec P = Prec::Default , bool StrictlyWorse = false  ) const inline Definition at line 275 of file ItaniumDemangle.h . References Default , getPrecedence() , OutputBuffer , P , and print() . Referenced by llvm::DOTGraphTraits< DOTFuncInfo * >::getBBName() , getSimpleNodeName() , llvm::operator<<() , llvm::VPIRMetadata::print() , and llvm::SimpleNodeLabelString() . ◆  printInitListAsType() virtual bool Node::printInitListAsType ( OutputBuffer & , const NodeArray &  ) const inline virtual Reimplemented in ArrayType . Definition at line 295 of file ItaniumDemangle.h . References OutputBuffer . ◆  visit() template<typename Fn> void Node::visit ( Fn F ) const Visit the most-derived object corresponding to this object. Visit the node. Calls F(P) , where P is the node cast to the appropriate derived class. Definition at line 2639 of file ItaniumDemangle.h . References DEMANGLE_ASSERT , and F . Friends And Related Symbol Documentation ◆  OutputBuffer friend class OutputBuffer friend Definition at line 309 of file ItaniumDemangle.h . References OutputBuffer . Referenced by ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , hasArray() , ArrayType::hasArraySlow() , ForwardTemplateReference::hasArraySlow() , hasArraySlow() , ParameterPack::hasArraySlow() , QualType::hasArraySlow() , hasFunction() , ForwardTemplateReference::hasFunctionSlow() , FunctionEncoding::hasFunctionSlow() , FunctionType::hasFunctionSlow() , hasFunctionSlow() , ParameterPack::hasFunctionSlow() , QualType::hasFunctionSlow() , hasRHSComponent() , ArrayType::hasRHSComponentSlow() , ForwardTemplateReference::hasRHSComponentSlow() , FunctionEncoding::hasRHSComponentSlow() , FunctionType::hasRHSComponentSlow() , hasRHSComponentSlow() , ParameterPack::hasRHSComponentSlow() , PointerToMemberType::hasRHSComponentSlow() , PointerType::hasRHSComponentSlow() , QualType::hasRHSComponentSlow() , ReferenceType::hasRHSComponentSlow() , OutputBuffer , print() , printAsOperand() , ClosureTypeName::printDeclarator() , ArrayType::printInitListAsType() , printInitListAsType() , AbiTagAttr::printLeft() , ArraySubscriptExpr::printLeft() , ArrayType::printLeft() , BinaryExpr::printLeft() , BinaryFPType::printLeft() , BitIntType::printLeft() , BoolExpr::printLeft() , BracedExpr::printLeft() , BracedRangeExpr::printLeft() , CallExpr::printLeft() , CastExpr::printLeft() , ClosureTypeName::printLeft() , ConditionalExpr::printLeft() , ConstrainedTypeTemplateParamDecl::printLeft() , ConversionExpr::printLeft() , ConversionOperatorType::printLeft() , CtorDtorName::printLeft() , CtorVtableSpecialName::printLeft() , DeleteExpr::printLeft() , DotSuffix::printLeft() , DtorName::printLeft() , DynamicExceptionSpec::printLeft() , ElaboratedTypeSpefType::printLeft() , EnableIfAttr::printLeft() , EnclosingExpr::printLeft() , EnumLiteral::printLeft() , ExplicitObjectParameter::printLeft() , ExprRequirement::printLeft() , FloatLiteralImpl< float >::printLeft() , FoldExpr::printLeft() , ForwardTemplateReference::printLeft() , FunctionEncoding::printLeft() , FunctionParam::printLeft() , FunctionType::printLeft() , GlobalQualifiedName::printLeft() , InitListExpr::printLeft() , IntegerLiteral::printLeft() , LambdaExpr::printLeft() , LiteralOperator::printLeft() , LocalName::printLeft() , MemberExpr::printLeft() , MemberLikeFriendName::printLeft() , ModuleEntity::printLeft() , ModuleName::printLeft() , NameType::printLeft() , NameWithTemplateArgs::printLeft() , NestedName::printLeft() , NestedRequirement::printLeft() , NewExpr::printLeft() , NodeArrayNode::printLeft() , NoexceptSpec::printLeft() , NonTypeTemplateParamDecl::printLeft() , ObjCProtoName::printLeft() , ParameterPack::printLeft() , ParameterPackExpansion::printLeft() , PixelVectorType::printLeft() , PointerToMemberConversionExpr::printLeft() , PointerToMemberType::printLeft() , PointerType::printLeft() , PostfixExpr::printLeft() , PostfixQualifiedType::printLeft() , PrefixExpr::printLeft() , QualifiedName::printLeft() , QualType::printLeft() , ReferenceType::printLeft() , RequiresExpr::printLeft() , SizeofParamPackExpr::printLeft() , SpecialName::printLeft() , SpecialSubstitution::printLeft() , StringLiteral::printLeft() , StructuredBindingName::printLeft() , SubobjectExpr::printLeft() , SyntheticTemplateParamName::printLeft() , TemplateArgs::printLeft() , TemplateArgumentPack::printLeft() , TemplateParamPackDecl::printLeft() , TemplateParamQualifiedArg::printLeft() , TemplateTemplateParamDecl::printLeft() , ThrowExpr::printLeft() , TransformedType::printLeft() , TypeRequirement::printLeft() , TypeTemplateParamDecl::printLeft() , UnnamedTypeName::printLeft() , VectorType::printLeft() , VendorExtQualType::printLeft() , QualType::printQuals() , ArrayType::printRight() , ConstrainedTypeTemplateParamDecl::printRight() , ForwardTemplateReference::printRight() , FunctionEncoding::printRight() , FunctionType::printRight() , NonTypeTemplateParamDecl::printRight() , ParameterPack::printRight() , PointerToMemberType::printRight() , PointerType::printRight() , QualType::printRight() , ReferenceType::printRight() , TemplateParamPackDecl::printRight() , TemplateTemplateParamDecl::printRight() , and TypeTemplateParamDecl::printRight() . Member Data Documentation ◆  ArrayCache Cache Node::ArrayCache protected Track if this node is a (possibly qualified) array type. This can affect how we format the output string. Definition at line 214 of file ItaniumDemangle.h . Referenced by getArrayCache() , hasArray() , Node() , and ParameterPack::ParameterPack() . ◆  FunctionCache Cache Node::FunctionCache protected Track if this node is a (possibly qualified) function type. This can affect how we format the output string. Definition at line 218 of file ItaniumDemangle.h . Referenced by getFunctionCache() , hasFunction() , Node() , and ParameterPack::ParameterPack() . ◆  RHSComponentCache Cache Node::RHSComponentCache protected Tracks if this node has a component on its right side, in which case we need to call printRight. Definition at line 210 of file ItaniumDemangle.h . Referenced by getRHSComponentCache() , hasRHSComponent() , Node() , ParameterPack::ParameterPack() , and print() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Scientific-Python:-Transitioning-from-MATLAB-to-Python | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Why-we-need-Numpy | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNode.html#a98a4fbc0165eb9a4516774ad17c91d27 | LLVM: Node Class Reference LLVM  22.0.0git Public Types | Public Member Functions | Protected Attributes | Friends | List of all members Node Class Reference abstract #include " llvm/Demangle/ItaniumDemangle.h " Inherited by FloatLiteralImpl< float > , FloatLiteralImpl< double > , FloatLiteralImpl< long double > , AbiTagAttr , ArraySubscriptExpr , ArrayType , BinaryExpr , BinaryFPType , BitIntType , BoolExpr , BracedExpr , BracedRangeExpr , CallExpr , CastExpr , ClosureTypeName , ConditionalExpr , ConstrainedTypeTemplateParamDecl , ConversionExpr , ConversionOperatorType , CtorDtorName , CtorVtableSpecialName , DeleteExpr , DotSuffix , DtorName , DynamicExceptionSpec , ElaboratedTypeSpefType , EnableIfAttr , EnclosingExpr , EnumLiteral , ExpandedSpecialSubstitution , ExplicitObjectParameter , ExprRequirement , FloatLiteralImpl< Float > , FoldExpr , ForwardTemplateReference , FunctionEncoding , FunctionParam , FunctionType , GlobalQualifiedName , InitListExpr , IntegerLiteral , LambdaExpr , LiteralOperator , LocalName , MemberExpr , MemberLikeFriendName , ModuleEntity , ModuleName , NameType , NameWithTemplateArgs , NestedName , NestedRequirement , NewExpr , NodeArrayNode , NoexceptSpec , NonTypeTemplateParamDecl , ObjCProtoName , ParameterPack , ParameterPackExpansion , PixelVectorType , PointerToMemberConversionExpr , PointerToMemberType , PointerType , PostfixExpr , PostfixQualifiedType , PrefixExpr , QualType , QualifiedName , ReferenceType , RequiresExpr , SizeofParamPackExpr , SpecialName , StringLiteral , StructuredBindingName , SubobjectExpr , SyntheticTemplateParamName , TemplateArgs , TemplateArgumentPack , TemplateParamPackDecl , TemplateParamQualifiedArg , TemplateTemplateParamDecl , ThrowExpr , TransformedType , TypeRequirement , TypeTemplateParamDecl , UnnamedTypeName , VectorType , and VendorExtQualType . Public Types enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Public Member Functions   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Protected Attributes Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Friends class  OutputBuffer Detailed Description Definition at line 166 of file ItaniumDemangle.h . Member Enumeration Documentation ◆  Cache enum class Node::Cache : uint8_t strong Three-way bool to track a cached value. Unknown is possible if this node has an unexpanded parameter pack below it that may affect this cache. Enumerator Yes  No  Unknown  Definition at line 175 of file ItaniumDemangle.h . ◆  Kind enum Node::Kind : uint8_t Definition at line 168 of file ItaniumDemangle.h . ◆  Prec enum class Node::Prec : uint8_t strong Operator precedence for expression nodes. Used to determine required parens in expression emission. Enumerator Primary  Postfix  Unary  Cast  PtrMem  Multiplicative  Additive  Shift  Spaceship  Relational  Equality  And  Xor  Ior  AndIf  OrIf  Conditional  Assign  Comma  Default  Definition at line 179 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  Node() [1/2] Node::Node ( Kind K_ , Prec Precedence_ = Prec::Primary , Cache RHSComponentCache_ = Cache::No , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 221 of file ItaniumDemangle.h . References ArrayCache , FunctionCache , No , Primary , and RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , ArraySubscriptExpr::ArraySubscriptExpr() , ArrayType::ArrayType() , BinaryExpr::BinaryExpr() , BinaryFPType::BinaryFPType() , BitIntType::BitIntType() , BoolExpr::BoolExpr() , BracedExpr::BracedExpr() , BracedRangeExpr::BracedRangeExpr() , CallExpr::CallExpr() , CastExpr::CastExpr() , ClosureTypeName::ClosureTypeName() , ConditionalExpr::ConditionalExpr() , ConstrainedTypeTemplateParamDecl::ConstrainedTypeTemplateParamDecl() , ConversionExpr::ConversionExpr() , ConversionOperatorType::ConversionOperatorType() , CtorDtorName::CtorDtorName() , CtorVtableSpecialName::CtorVtableSpecialName() , DeleteExpr::DeleteExpr() , DotSuffix::DotSuffix() , DtorName::DtorName() , DynamicExceptionSpec::DynamicExceptionSpec() , ElaboratedTypeSpefType::ElaboratedTypeSpefType() , EnableIfAttr::EnableIfAttr() , EnclosingExpr::EnclosingExpr() , EnumLiteral::EnumLiteral() , ExpandedSpecialSubstitution::ExpandedSpecialSubstitution() , ExplicitObjectParameter::ExplicitObjectParameter() , ExprRequirement::ExprRequirement() , FloatLiteralImpl< float >::FloatLiteralImpl() , FoldExpr::FoldExpr() , ForwardTemplateReference::ForwardTemplateReference() , FunctionEncoding::FunctionEncoding() , FunctionParam::FunctionParam() , FunctionType::FunctionType() , TemplateParamQualifiedArg::getArg() , FunctionEncoding::getAttrs() , VectorType::getBaseType() , ParameterPackExpansion::getChild() , QualType::getChild() , VectorType::getDimension() , FunctionEncoding::getName() , PointerType::getPointee() , FunctionEncoding::getRequires() , FunctionEncoding::getReturnType() , ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , VendorExtQualType::getTA() , VendorExtQualType::getTy() , GlobalQualifiedName::GlobalQualifiedName() , InitListExpr::InitListExpr() , IntegerLiteral::IntegerLiteral() , LambdaExpr::LambdaExpr() , LiteralOperator::LiteralOperator() , LocalName::LocalName() , MemberExpr::MemberExpr() , MemberLikeFriendName::MemberLikeFriendName() , ModuleEntity::ModuleEntity() , ModuleName::ModuleName() , NameType::NameType() , NameWithTemplateArgs::NameWithTemplateArgs() , NestedName::NestedName() , NestedRequirement::NestedRequirement() , NewExpr::NewExpr() , Node() , NodeArrayNode::NodeArrayNode() , NoexceptSpec::NoexceptSpec() , NonTypeTemplateParamDecl::NonTypeTemplateParamDecl() , ObjCProtoName::ObjCProtoName() , ParameterPack::ParameterPack() , ParameterPackExpansion::ParameterPackExpansion() , PixelVectorType::PixelVectorType() , PointerToMemberConversionExpr::PointerToMemberConversionExpr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , PostfixExpr::PostfixExpr() , PostfixQualifiedType::PostfixQualifiedType() , PrefixExpr::PrefixExpr() , RequiresExpr::printLeft() , QualifiedName::QualifiedName() , QualType::QualType() , ReferenceType::ReferenceType() , RequiresExpr::RequiresExpr() , SizeofParamPackExpr::SizeofParamPackExpr() , SpecialName::SpecialName() , StringLiteral::StringLiteral() , StructuredBindingName::StructuredBindingName() , SubobjectExpr::SubobjectExpr() , SyntheticTemplateParamName::SyntheticTemplateParamName() , TemplateArgs::TemplateArgs() , TemplateArgumentPack::TemplateArgumentPack() , TemplateParamPackDecl::TemplateParamPackDecl() , TemplateParamQualifiedArg::TemplateParamQualifiedArg() , TemplateTemplateParamDecl::TemplateTemplateParamDecl() , ThrowExpr::ThrowExpr() , TransformedType::TransformedType() , TypeRequirement::TypeRequirement() , TypeTemplateParamDecl::TypeTemplateParamDecl() , UnnamedTypeName::UnnamedTypeName() , VectorType::VectorType() , and VendorExtQualType::VendorExtQualType() . ◆  Node() [2/2] Node::Node ( Kind K_ , Cache RHSComponentCache_ , Cache ArrayCache_ = Cache::No , Cache FunctionCache_ = Cache::No  ) inline Definition at line 226 of file ItaniumDemangle.h . References No , Node() , and Primary . ◆  ~Node() virtual Node::~Node ( ) virtual default Member Function Documentation ◆  dump() DEMANGLE_DUMP_METHOD void Node::dump ( ) const References DEMANGLE_DUMP_METHOD . Referenced by llvm::DAGTypeLegalizer::run() , and llvm::RISCVDAGToDAGISel::Select() . ◆  getArrayCache() Cache Node::getArrayCache ( ) const inline Definition at line 262 of file ItaniumDemangle.h . References ArrayCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getBaseName() virtual std::string_view Node::getBaseName ( ) const inline virtual Reimplemented in AbiTagAttr , ExpandedSpecialSubstitution , GlobalQualifiedName , MemberLikeFriendName , ModuleEntity , NameType , NameWithTemplateArgs , NestedName , QualifiedName , and SpecialSubstitution . Definition at line 299 of file ItaniumDemangle.h . ◆  getFunctionCache() Cache Node::getFunctionCache ( ) const inline Definition at line 263 of file ItaniumDemangle.h . References FunctionCache . Referenced by AbiTagAttr::AbiTagAttr() , and QualType::QualType() . ◆  getKind() Kind Node::getKind ( ) const inline Definition at line 258 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseCtorDtorName() , AbstractManglingParser< Derived, Alloc >::parseNestedName() , AbstractManglingParser< Derived, Alloc >::parseTemplateArgs() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnscopedName() , NodeArray::printAsString() , and llvm::msgpack::Document::writeToBlob() . ◆  getPrecedence() Prec Node::getPrecedence ( ) const inline Definition at line 260 of file ItaniumDemangle.h . Referenced by ArraySubscriptExpr::match() , BinaryExpr::match() , CallExpr::match() , CastExpr::match() , ConditionalExpr::match() , ConversionExpr::match() , DeleteExpr::match() , EnclosingExpr::match() , MemberExpr::match() , NewExpr::match() , PointerToMemberConversionExpr::match() , PostfixExpr::match() , PrefixExpr::match() , printAsOperand() , ArraySubscriptExpr::printLeft() , BinaryExpr::printLeft() , ConditionalExpr::printLeft() , MemberExpr::printLeft() , PostfixExpr::printLeft() , and PrefixExpr::printLeft() . ◆  getRHSComponentCache() Cache Node::getRHSComponentCache ( ) const inline Definition at line 261 of file ItaniumDemangle.h . References RHSComponentCache . Referenced by AbiTagAttr::AbiTagAttr() , PointerToMemberType::PointerToMemberType() , PointerType::PointerType() , QualType::QualType() , and ReferenceType::ReferenceType() . ◆  getSyntaxNode() virtual const Node * Node::getSyntaxNode ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , and ParameterPack . Definition at line 271 of file ItaniumDemangle.h . References Node() , and OutputBuffer . ◆  hasArray() bool Node::hasArray ( OutputBuffer & OB ) const inline Definition at line 246 of file ItaniumDemangle.h . References ArrayCache , hasArraySlow() , OutputBuffer , Unknown , and Yes . ◆  hasArraySlow() virtual bool Node::hasArraySlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , ParameterPack , and QualType . Definition at line 266 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasArray() . ◆  hasFunction() bool Node::hasFunction ( OutputBuffer & OB ) const inline Definition at line 252 of file ItaniumDemangle.h . References FunctionCache , hasFunctionSlow() , OutputBuffer , Unknown , and Yes . ◆  hasFunctionSlow() virtual bool Node::hasFunctionSlow ( OutputBuffer & ) const inline virtual Reimplemented in ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , and QualType . Definition at line 267 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasFunction() . ◆  hasRHSComponent() bool Node::hasRHSComponent ( OutputBuffer & OB ) const inline Definition at line 240 of file ItaniumDemangle.h . References hasRHSComponentSlow() , OutputBuffer , RHSComponentCache , Unknown , and Yes . ◆  hasRHSComponentSlow() virtual bool Node::hasRHSComponentSlow ( OutputBuffer & ) const inline virtual Reimplemented in ArrayType , ForwardTemplateReference , FunctionEncoding , FunctionType , ParameterPack , PointerToMemberType , PointerType , QualType , and ReferenceType . Definition at line 265 of file ItaniumDemangle.h . References OutputBuffer . Referenced by hasRHSComponent() . ◆  print() void Node::print ( OutputBuffer & OB ) const inline Definition at line 286 of file ItaniumDemangle.h . References No , OutputBuffer , and RHSComponentCache . Referenced by llvm::ItaniumPartialDemangler::getFunctionDeclContextName() , llvm::DOTGraphTraits< AADepGraph * >::getNodeLabel() , llvm::DOTGraphTraits< const MachineFunction * >::getNodeLabel() , llvm::itaniumDemangle() , printAsOperand() , FoldExpr::printLeft() , and printNode() . ◆  printAsOperand() void Node::printAsOperand ( OutputBuffer & OB , Prec P = Prec::Default , bool StrictlyWorse = false  ) const inline Definition at line 275 of file ItaniumDemangle.h . References Default , getPrecedence() , OutputBuffer , P , and print() . Referenced by llvm::DOTGraphTraits< DOTFuncInfo * >::getBBName() , getSimpleNodeName() , llvm::operator<<() , llvm::VPIRMetadata::print() , and llvm::SimpleNodeLabelString() . ◆  printInitListAsType() virtual bool Node::printInitListAsType ( OutputBuffer & , const NodeArray &  ) const inline virtual Reimplemented in ArrayType . Definition at line 295 of file ItaniumDemangle.h . References OutputBuffer . ◆  visit() template<typename Fn> void Node::visit ( Fn F ) const Visit the most-derived object corresponding to this object. Visit the node. Calls F(P) , where P is the node cast to the appropriate derived class. Definition at line 2639 of file ItaniumDemangle.h . References DEMANGLE_ASSERT , and F . Friends And Related Symbol Documentation ◆  OutputBuffer friend class OutputBuffer friend Definition at line 309 of file ItaniumDemangle.h . References OutputBuffer . Referenced by ForwardTemplateReference::getSyntaxNode() , getSyntaxNode() , ParameterPack::getSyntaxNode() , hasArray() , ArrayType::hasArraySlow() , ForwardTemplateReference::hasArraySlow() , hasArraySlow() , ParameterPack::hasArraySlow() , QualType::hasArraySlow() , hasFunction() , ForwardTemplateReference::hasFunctionSlow() , FunctionEncoding::hasFunctionSlow() , FunctionType::hasFunctionSlow() , hasFunctionSlow() , ParameterPack::hasFunctionSlow() , QualType::hasFunctionSlow() , hasRHSComponent() , ArrayType::hasRHSComponentSlow() , ForwardTemplateReference::hasRHSComponentSlow() , FunctionEncoding::hasRHSComponentSlow() , FunctionType::hasRHSComponentSlow() , hasRHSComponentSlow() , ParameterPack::hasRHSComponentSlow() , PointerToMemberType::hasRHSComponentSlow() , PointerType::hasRHSComponentSlow() , QualType::hasRHSComponentSlow() , ReferenceType::hasRHSComponentSlow() , OutputBuffer , print() , printAsOperand() , ClosureTypeName::printDeclarator() , ArrayType::printInitListAsType() , printInitListAsType() , AbiTagAttr::printLeft() , ArraySubscriptExpr::printLeft() , ArrayType::printLeft() , BinaryExpr::printLeft() , BinaryFPType::printLeft() , BitIntType::printLeft() , BoolExpr::printLeft() , BracedExpr::printLeft() , BracedRangeExpr::printLeft() , CallExpr::printLeft() , CastExpr::printLeft() , ClosureTypeName::printLeft() , ConditionalExpr::printLeft() , ConstrainedTypeTemplateParamDecl::printLeft() , ConversionExpr::printLeft() , ConversionOperatorType::printLeft() , CtorDtorName::printLeft() , CtorVtableSpecialName::printLeft() , DeleteExpr::printLeft() , DotSuffix::printLeft() , DtorName::printLeft() , DynamicExceptionSpec::printLeft() , ElaboratedTypeSpefType::printLeft() , EnableIfAttr::printLeft() , EnclosingExpr::printLeft() , EnumLiteral::printLeft() , ExplicitObjectParameter::printLeft() , ExprRequirement::printLeft() , FloatLiteralImpl< float >::printLeft() , FoldExpr::printLeft() , ForwardTemplateReference::printLeft() , FunctionEncoding::printLeft() , FunctionParam::printLeft() , FunctionType::printLeft() , GlobalQualifiedName::printLeft() , InitListExpr::printLeft() , IntegerLiteral::printLeft() , LambdaExpr::printLeft() , LiteralOperator::printLeft() , LocalName::printLeft() , MemberExpr::printLeft() , MemberLikeFriendName::printLeft() , ModuleEntity::printLeft() , ModuleName::printLeft() , NameType::printLeft() , NameWithTemplateArgs::printLeft() , NestedName::printLeft() , NestedRequirement::printLeft() , NewExpr::printLeft() , NodeArrayNode::printLeft() , NoexceptSpec::printLeft() , NonTypeTemplateParamDecl::printLeft() , ObjCProtoName::printLeft() , ParameterPack::printLeft() , ParameterPackExpansion::printLeft() , PixelVectorType::printLeft() , PointerToMemberConversionExpr::printLeft() , PointerToMemberType::printLeft() , PointerType::printLeft() , PostfixExpr::printLeft() , PostfixQualifiedType::printLeft() , PrefixExpr::printLeft() , QualifiedName::printLeft() , QualType::printLeft() , ReferenceType::printLeft() , RequiresExpr::printLeft() , SizeofParamPackExpr::printLeft() , SpecialName::printLeft() , SpecialSubstitution::printLeft() , StringLiteral::printLeft() , StructuredBindingName::printLeft() , SubobjectExpr::printLeft() , SyntheticTemplateParamName::printLeft() , TemplateArgs::printLeft() , TemplateArgumentPack::printLeft() , TemplateParamPackDecl::printLeft() , TemplateParamQualifiedArg::printLeft() , TemplateTemplateParamDecl::printLeft() , ThrowExpr::printLeft() , TransformedType::printLeft() , TypeRequirement::printLeft() , TypeTemplateParamDecl::printLeft() , UnnamedTypeName::printLeft() , VectorType::printLeft() , VendorExtQualType::printLeft() , QualType::printQuals() , ArrayType::printRight() , ConstrainedTypeTemplateParamDecl::printRight() , ForwardTemplateReference::printRight() , FunctionEncoding::printRight() , FunctionType::printRight() , NonTypeTemplateParamDecl::printRight() , ParameterPack::printRight() , PointerToMemberType::printRight() , PointerType::printRight() , QualType::printRight() , ReferenceType::printRight() , TemplateParamPackDecl::printRight() , TemplateTemplateParamDecl::printRight() , and TypeTemplateParamDecl::printRight() . Member Data Documentation ◆  ArrayCache Cache Node::ArrayCache protected Track if this node is a (possibly qualified) array type. This can affect how we format the output string. Definition at line 214 of file ItaniumDemangle.h . Referenced by getArrayCache() , hasArray() , Node() , and ParameterPack::ParameterPack() . ◆  FunctionCache Cache Node::FunctionCache protected Track if this node is a (possibly qualified) function type. This can affect how we format the output string. Definition at line 218 of file ItaniumDemangle.h . Referenced by getFunctionCache() , hasFunction() , Node() , and ParameterPack::ParameterPack() . ◆  RHSComponentCache Cache Node::RHSComponentCache protected Tracks if this node has a component on its right side, in which case we need to call printRight. Definition at line 210 of file ItaniumDemangle.h . Referenced by getRHSComponentCache() , hasRHSComponent() , Node() , ParameterPack::ParameterPack() , and print() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Advanced | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://www.php.net/x-myracloud-5958a2bbbed300a9b9ac631223924e0b/1768296252.681 | PHP update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box A popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world. What's new in 8.5 Download 8.5.1 · Changelog · Upgrading 8.4.16 · Changelog · Upgrading 8.3.29 · Changelog · Upgrading 8.2.30 · Changelog · Upgrading 18 Dec 2025 PHP 8.1.34 Released! The PHP development team announces the immediate availability of PHP 8.1.34. This is a security release. All PHP 8.1 users are encouraged to upgrade to this version. For source downloads of PHP 8.1.34 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.4.16 Released! The PHP development team announces the immediate availability of PHP 8.4.16. This is a security release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.16 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.2.30 Released! The PHP development team announces the immediate availability of PHP 8.2.30. This is a security release. All PHP 8.2 users are encouraged to upgrade to this version. For source downloads of PHP 8.2.30 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.3.29 Released! The PHP development team announces the immediate availability of PHP 8.3.29. This is a security release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.29 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.5.1 Released! The PHP development team announces the immediate availability of PHP 8.5.1. This is a security release. All PHP 8.5 users are encouraged to upgrade to this version. For source downloads of PHP 8.5.1 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.5.0 Released! The PHP development team announces the immediate availability of PHP 8.5.0. This release marks the latest minor release of the PHP language. PHP 8.5 comes with numerous improvements and new features such as: New "URI" extension New pipe operator (|>) Clone With New #[\NoDiscard] attribute Support for closures, casts, and first class callables in constant expressions And much much more... For source downloads of PHP 8.5.0 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . The migration guide is available in the PHP Manual. Please consult it for the detailed list of new features and backward incompatible changes. Kudos to all the contributors and supporters! 20 Nov 2025 PHP 8.4.15 Released! The PHP development team announces the immediate availability of PHP 8.4.15. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.15 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.3.28 Released! The PHP development team announces the immediate availability of PHP 8.3.28. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.28 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 13 Nov 2025 PHP 8.5.0 RC 5 available for testing The PHP team is pleased to announce the fifth release candidate of PHP 8.5.0, RC 5. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC5, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 06 Nov 2025 PHP 8.5.0 RC4 available for testing The PHP team is pleased to announce the final planned release candidate of PHP 8.5.0, RC 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC4, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 23 Oct 2025 PHP 8.3.27 Released! The PHP development team announces the immediate availability of PHP 8.3.27. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.27 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.4.14 Released! The PHP development team announces the immediate availability of PHP 8.4.14. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.14 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.5.0 RC 3 available for testing The PHP team is pleased to announce the third release candidate of PHP 8.5.0, RC 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC4, planned for 6 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 09 Oct 2025 PHP 8.5.0 RC 2 available for testing The PHP team is pleased to announce the second release candidate of PHP 8.5.0, RC 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC2, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC3, planned for 23 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.5.0 RC 1 available for testing The PHP team is pleased to announce the first release candidate of PHP 8.5.0, RC 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC1, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC2, planned for 9 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.3.26 Released! The PHP development team announces the immediate availability of PHP 8.3.26. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.26 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 25 Sep 2025 PHP 8.4.13 Released! The PHP development team announces the immediate availability of PHP 8.4.13. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.13 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 11 Sep 2025 PHP 8.5.0 Beta 3 available for testing The PHP team is pleased to announce the third beta release of PHP 8.5.0, Beta 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC1, planned for 25 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.5.0 Beta 2 available for testing The PHP team is pleased to announce the second beta release of PHP 8.5.0, Beta 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 2 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 3, planned for 11 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.3.25 Released! The PHP development team announces the immediate availability of PHP 8.3.25. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.25 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 28 Aug 2025 PHP 8.4.12 Released! The PHP development team announces the immediate availability of PHP 8.4.12. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.12 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 14 Aug 2025 PHP 8.5.0 Beta 1 available for testing The PHP team is pleased to announce the first beta release of PHP 8.5.0, Beta 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 1 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 2, planned for 28 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 01 Aug 2025 PHP 8.5.0 Alpha 4 available for testing The PHP team is pleased to announce the third testing release of PHP 8.5.0, Alpha 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Alpha 4 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 1, planned for 14 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 31 Jul 2025 PHP 8.4.11 Released! The PHP development team announces the immediate availability of PHP 8.4.11. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.11 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 31 Jul 2025 PHP 8.3.24 Released! The PHP development team announces the immediate availability of PHP 8.3.24. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.24 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . Older News Entries The PHP Foundation The PHP Foundation is a collective of people and organizations, united in the mission to ensure the long-term prosperity of the PHP language. Donate Upcoming conferences International PHP Conference Berlin 2026 Laravel Live Japan Conferences calling for papers Dutch PHP Conference 2026 User Group Events Special Thanks Social media @official_php @php@fosstodon.org @phpnet Copyright © 2001-2026 The PHP Group My PHP.net Contact Other PHP.net sites Privacy policy View Source ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://de.linkedin.com/company/ngdeconf#main-content | NG-DE Conference by workshops.de | LinkedIn Weiter zum Hauptinhalt LinkedIn Artikel Personen E-Learning Jobs Spiele Einloggen Jetzt anmelden NG-DE Conference by workshops.de Technologie, Information und Internet NG-DE is the community-driven Angular conference in Germany organized by workshops.de. We are back in 2026 in Berlin! Folgen alle 2 Mitarbeiter:innen anzeigen Dieses Unternehmen melden Info NG-DE is the first community-driven Angular conference in Germany. We will run the opening event in Berlin, GLS Campus Berlin on 6th and 7th November 2025. A bunch of one-day workshops are planned alongside the conference which can be booked separately. Website https://ng-de.org Externer Link zu NG-DE Conference by workshops.de Branche Technologie, Information und Internet Größe 2–10 Beschäftigte Hauptsitz Berlin Art Nonprofit Gegründet 2018 Spezialgebiete Angular, JavaScript, Frontend Development, TypeScript, Community, Web Development, Progressive Web Apps, Conference und Event Orte Primär Berlin, DE Wegbeschreibung Beschäftigte von NG-DE Conference by workshops.de Peter M. Alle Beschäftigten anzeigen Updates NG-DE Conference by workshops.de 510 Follower:innen 3 Wochen Diesen Beitrag melden 🎅 Ho Ho Ho, Angular Community! We've got an early Christmas gift for you! NG-DE 2025 conference talks are now available on YouTube! 🎬 We just released: 🎯 Mark Thompson : Opening keynote that set the stage for an incredible conference 🎯 Matthieu Riegler : Game-changing session on making forms painless (yes, really!) 🎯 Our panel discussion with brilliant Q&A moments starring Gregor Woiwode , Kasia Biernat-Kluba , Dr. Jim Sellmeijer , and more... Starting January 2026, we'll be continuously releasing more talks. 🔔 Subscribe here: https://lnkd.in/eU_J5Pws What was your favorite moment from NG-DE 2025? Let us know in the comments! - YouTube youtube.com 10 1 Kommentar Gefällt mir Kommentieren Teilen NG-DE Conference by workshops.de hat dies direkt geteilt Brygida Fiejdasz 2 Monate Diesen Beitrag melden Last week, I had the incredible opportunity to speak at the NG-DE Conference , where I discussed Angular’s change detection and zoneless mode. It was such an amazing two days 😍. I loved reconnecting with familiar faces and meeting so many inspiring new people! I want to give a huge thank you to Ali Elderov for being such a fantastic captain on stage🔥 I really couldn’t have done it without you. And, of course, a big thank you to the organizers for inviting me and putting together such an outstanding event. Looking back, I feel inspired, energized, and so thankful for the connections and memories I’ve gained from this experience 🧡. +1 61 6 Kommentare Gefällt mir Kommentieren Teilen NG-DE Conference by workshops.de hat dies direkt geteilt Marko Stanimirović 2 Monate Diesen Beitrag melden Had an amazing time at the NG-DE Conference last week! 🤘 It was a pleasure to deliver a talk and run our NgRx SignalStore workshop together with Rainer Hahnekamp . Huge thanks to the organizers for an outstanding event, the emcees for doing a great job, all the speakers for their inspiring sessions, and the audience for bringing incredible energy and engagement throughout the conference! +1 91 3 Kommentare Gefällt mir Kommentieren Teilen NG-DE Conference by workshops.de hat dies direkt geteilt Kasia Biernat-Kluba 2 Monate Diesen Beitrag melden Last week I had a pleasure of speaking at the NG-DE Conference in Berlin! 🔥 I was honored not only to share my talk on “Code that writes Code” but also to participate in a discussion panel alongside Mark Thompson , Matthieu Riegler , Dr. Jim Sellmeijer and Gregor Woiwode ! It was my first time on this conference but hopefully not the last! The truth is I had NG-DE on my radar since 2019, but there was always something in the way. Dates collision, coronavirus lockdowns, budget limitations etc. I’m so so happy I made it this year. I’d like to share a huge shoutout to the organizers - everything was just perfect. Special thanks to Ola Gasidlo-Brändel - the best MC we could get and a good soul on the backstage, cheering me up before my talk! And last, I wouldn’t be myself if I didn’t mention the amazing, vegan catering. I’m not strictly vegetarian anymore but I always appreciate excellent vegan food. I’m so happy to see such an event being held in a sustainable way 🌱 🌎 120 9 Kommentare Gefällt mir Kommentieren Teilen NG-DE Conference by workshops.de 510 Follower:innen 2 Monate Diesen Beitrag melden The NG-DE vibes continue! 🙌 Join the community live at 9:30 AM CET and don’t miss today’s talks on YouTube 🎥 👉 https://lnkd.in/etx5ZXwb #Angular #AngularCommunity #LiveStream #NGDE #NGConf #WebDevelopment #DeveloperCommunity #WeLoveAngular #DevLife #MeetTheCommunity #CodeTogether #DevConference #TechConference #AngularDevelopers #AngularEvent #AngularTalks #WebDevCommunity 10 1 Kommentar Gefällt mir Kommentieren Teilen NG-DE Conference by workshops.de 510 Follower:innen 2 Monate Diesen Beitrag melden Missed NG-DE in Berlin? Don’t miss out completely! Tune in to our live streams on YouTube and be part of the community from anywhere 🌍 👉 Link to the Livestream : https://lnkd.in/ekzEscmK #Angular #LiveStream #NGDE 11 Gefällt mir Kommentieren Teilen NG-DE Conference by workshops.de 510 Follower:innen 2 Monate Diesen Beitrag melden Hey Angular Community! E.ON Digital Technology (our main sponsor this year AGAIN 💕) supports us with 10 free tickets for NG-DE Conference 2025 in Berlin – all you need to do is apply! Why are they doing this? At E.ON Digital Technology, they believe that innovation grows when people share knowledge and connect with each other. They are Tech to the Core – and want to empower others to grow through technology as well. What awaits you: • Workshop Day: November 5th – Hands-on Workshop "Build Your First Chatbot with Angular and MCP: A Hands-On Introduction to Conversational AI" • Conference: 2 days packed with Angular insights, best practices, and community networking • Location: Hotel Oderberger (GLS Campus Berlin) in Prenzlauer Berg Conference Website: https://ng-de.org/ NG-DE is a highlight every year – the chance to meet people who are just as passionate about Angular as you are. Whether you're reconnecting with old friends or making new contacts: the community is what makes this conference special. How can you participate? Simply apply here: https://lnkd.in/dncxD8HX Go for it, apply, and with a bit of luck we'll see you in Berlin this November! Good luck! Best regards, Robin E:ON Gewinnspiel zur NG-DE 2025 docs.google.com 5 1 Kommentar Gefällt mir Kommentieren Teilen NG-DE Conference by workshops.de 510 Follower:innen 2 Monate Diesen Beitrag melden 🚨 Flash Sale – only 3 hours left! 🚨 We’re thrilled to welcome everyone back for NG-DE 2025, happening October 5th–7th in Berlin! 🇩🇪 Join the Angular community from around the world for three amazing days packed with talks, workshops, and new connections. ✨ BONUS: This year, we’re introducing a brand-new AI Stage — exploring the future of Angular + AI! 🎟️ Don’t wait — grab your ticket now at https://ng-de.org and save big before the flash sale ends! C2PA-Informationen anzeigen 3 Gefällt mir Kommentieren Teilen NG-DE Conference by workshops.de 510 Follower:innen 2 Monate Diesen Beitrag melden 🚀 This is the final piece of the NG-DE puzzle you’ve been waiting for! We’re excited to launch our final special offer — and it’s only available for the next 24 hours. 🎟️ Get our most valuable combi ticket with 25% off and secure your spot at one of Europe’s top Angular & AI events. 💰 Save 300 € — or enjoy half a workshop day for free 🧠 Bonus: Exclusive access to the AI Stage, where you’ll get the latest insights and tools to elevate your software development workflow. ⚡ Don’t miss this — after 24 hours, the offer is gone. 👉 Get your ticket now https://ng-de.org … mehr We are adding the last final peace to the NG-DE Puzzle 7 1 Kommentar Gefällt mir Kommentieren Teilen NG-DE Conference by workshops.de 510 Follower:innen 3 Monate Diesen Beitrag melden The countdown is running... C2PA-Informationen anzeigen 14 1 Kommentar Gefällt mir Kommentieren Teilen Einfach anmelden, damit Sie nichts verpassen. Personen von NG-DE Conference by workshops.de finden, die Sie kennen Persönliche Jobempfehlungen erhalten Alle Updates, News und Artikel anzeigen Jetzt anmelden Ähnliche Seiten workshops.de Bildungsverwaltungsprogramme angular.love Gemeinnützige Organisationen Warszawa, Mazowieckie Coding Challenges Softwareentwicklung Westbury, Wiltshire Mind*Space Therapie Krankenhäuser und Gesundheitseinrichtungen Berlin, Berlin journai Softwareentwicklung Philadelphia , Pennsylvania qupaya technologies GmbH IT-Dienstleistungen und IT-Beratung Nuremberg, Bavaria Scriptbakery AI IT-Dienstleistungen und IT-Beratung Freiburg im Breisgau, Baden-Württemberg Karlsruher Tafel E.V. Karlsruhe, Baden-Württemberg AAIC - Applied AI Conference IT und Services WIEN, Vienna OxidizeConf IT-Dienstleistungen und IT-Beratung Berlin, Berlin Mehr ähnliche Seiten anzeigen Weniger ähnliche Seiten anzeigen Jobs durchsuchen Entwickler-Jobs 21.496 freie Stellen LinkedIn © 2026 Info Barrierefreiheit Nutzervereinbarung Datenschutzrichtlinie Cookie-Richtlinie Copyright-Richtlinie Markenrichtlinine Einstellungen für Nichtmitglieder Community-Richtlinien العربية (Arabisch) বাংলা (Bengali) Čeština (Tschechisch) Dansk (Dänisch) Deutsch Ελανεκα (Griechisch) English (Englisch) Español (Spanisch) فارسی (Persisch) Suomi (Finnisch) Français (Französisch) हिंदी (Hindi) Magyar (Ungarisch) Bahasa Indonesia (Indonesisch) Italiano (Italienisch) עברית (Hebräisch) 日本語 (Japanisch) 한국어 (Koreanisch) मराठी (Marathi) Bahasa Malaysia (Malaysisch) Nederlands (Niederländisch) Norsk (Norwegisch) ਪੰਜਾਬੀ (Punjabi) Polski (Polnisch) Português (Portugiesisch) Română (Rumänisch) Русский (Russisch) Svenska (Schwedisch) తెలుగు (Telugu) ภาษาไทย (Thai) Tagalog (Tagalog) Türkçe (Türkisch) Українська (Ukrainisch) Tiếng Việt (Vietnamesisch) 简体中文 (Chinesisch vereinfacht) 正體中文 (Chinesisch traditionell) Sprache Zustimmen und LinkedIn beitreten Wenn Sie auf „Weiter“ klicken, um Mitglied zu werden oder sich einzuloggen, stimmen Sie der Nutzervereinbarung , der Datenschutzrichtlinie und der Cookie-Richtlinie von LinkedIn zu. Loggen Sie sich ein, um zu sehen, wen Sie bereits bei NG-DE Conference by workshops.de kennen. Einloggen Schön, dass Sie wieder da sind E-Mail-Adresse/Telefon Passwort Einblenden Passwort vergessen? Einloggen oder Wenn Sie auf „Weiter“ klicken, um Mitglied zu werden oder sich einzuloggen, stimmen Sie der Nutzervereinbarung , der Datenschutzrichtlinie und der Cookie-Richtlinie von LinkedIn zu. Neu bei LinkedIn? Mitglied werden oder Neu bei LinkedIn? Mitglied werden Wenn Sie auf „Weiter“ klicken, um Mitglied zu werden oder sich einzuloggen, stimmen Sie der Nutzervereinbarung , der Datenschutzrichtlinie und der Cookie-Richtlinie von LinkedIn zu. | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#Functions | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://www.timeforkids.com/k1/topics/food-and-nutrition/ | TIME for Kids | Food and Nutrition | Topic | K-1 Skip to main content Search Articles by Grade level Grades K-1 Articles Grade 2 Articles Grades 3-4 Articles Grades 5-6 Articles Topics Animals Arts Ask Angela Books Business Careers Community Culture Debate Earth Science Education Election 2024 Engineering Environment Food and Nutrition Games Government History Holidays Inventions Movies and Television Music and Theater Nature News People Places Podcasts Science Service Stars Space Sports The Human Body The View Transportation Weather World Young Game Changers Your $ Financial Literacy Content Grade 4 Edition Grade 5-6 Edition For Grown-ups Resource Spotlight Also from TIME for Kids: Log In role: none user_age: none editions: The page you are about to enter is for grown-ups. Enter your birth date to continue. Month (MM) 01 02 03 04 05 06 07 08 09 10 11 12 Year (YYYY) 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 Submit Food and Nutrition World How We Eat March 10, 2022 People eat with different tools. Here are a few of them. Which do you use most often? Fork This fork has four prongs. You poke them into food to pick it up. You can also use a fork to… Audio World Pass the Rice March 10, 2022 People all over the world eat rice. Different countries have their own rice dishes. Below are five dishes from different parts of the world. Which would you like to try? Jambalaya is from the United States. Jambalaya is popular… Audio Spanish Environment Grow Your Own Garden March 10, 2022 Starting a garden might seem hard. TFK Kid Reporter Ian McKenna has some tips. They will get you growing in no time. • Decide what to grow. Grow vegetables. If you don’t like vegetables, try fruits or flowers. There are… Audio Environment Eat for the Earth March 10, 2022 Some food choices are better for the planet than others. They use less energy and fewer resources. Here are some environmentally friendly food tips. Shop Locally Shipping food a long way uses energy. Farmers’ markets sell food that was… Audio Spanish Health Summer Snacking May 21, 2021 Popsicles are a summer treat. But are they good fuel for playing outside? Here are some healthy snack ideas from cookbook author Katie Kimball. 1. Make a System. A snack schedule makes everyone happier. Create one with your family. Then… Audio World Breaking Bread October 15, 2020 Bread is a food made from flour and water. People have been eating bread for thousands of years. Different cultures make their own types of bread. Take a bread tour of the world. Pumpernickel is from Germany. This bread is… Audio Spanish World How to Make Tortillas October 15, 2020 A tortilla is a type of flatbread. Tortillas are an important part of Mexican food. Check out how a corn tortilla is made. Start with corn flour and water. Corn flour is ground corn. Make dough. Mix the… Audio United States Grab a Slice! March 6, 2020 How do you like your pizza? The answer could depend on where you live. Here are three different styles of the popular food. Dig in! New York-style pizza has a thin crust. It is often sold by the slice. Many… Audio United States Let's Eat! March 6, 2020 People in the United States enjoy many types of food. Here are five dishes that are specialties in different parts of the country. Which would you like to try? Hangtown fry is a fancy egg dish. It has oysters and… Audio Spanish Environment Amazing Apples September 6, 2019 This is apple season! Apples are ripe in the fall. They are ready to be picked and eaten. Join TIME for Kids on a trip to the orchard. Let’s learn about this fall fruit. At the Orchard Welcome to the… Audio Video Spanish Posts pagination 1 2 Next Contact us Privacy policy California privacy Terms of Service Subscribe CLASSROOM INTERNATIONAL © 2026 TIME USA, LLC. All Rights Reserved. Powered by WordPress.com VIP | 2026-01-13T09:30:39 |
https://nbviewer.jupyter.org/github/gestaltrevision/python_for_visres/blob/master/Part3/Part3_Scientific_Python.ipynb#The-ndarray-data-type | Jupyter Notebook Viewer Toggle navigation JUPYTER FAQ View as Code View on GitHub Execute on Binder Download Notebook python_for_visres Part3 Notebook Back to the main index Scientific Python: Transitioning from MATLAB to Python ¶ Part of the introductory series to using Python for Vision Research brought to you by the GestaltReVision group (KU Leuven, Belgium). This notebook is meant as an introduction to Python's essential scientific packages: Numpy, PIL, Matplotlib, and SciPy. There is more Python learning material available on our lab's wiki . Author: Maarten Demeyer Year: 2014 Copyright: Public Domain as in CC0 Contents ¶ A Quick Recap Data types Lists Functions Objects Numpy Why we need Numpy The ndarray data type shape and dtype Indexing and slicing Filling and manipulating arrays A few useful functions A small exercise A bit harder: The Gabor Boolean indexing Vectorizing a simulation PIL: the Python Imaging Library Loading and showing images Resizing, rotating, cropping and converting Advanced Saving Exercise Matplotlib Quick plots Saving to a file Visualizing arrays Multi-panel figures Exercise: Function plots Finer figure control Exercise: Add regression lines Scipy Statistics Fast Fourier Transform A Quick Recap ¶ Data types ¶ Depending on what kind of values you want to store, Python variables can be of different data types. For instance: In [ ]: my_int = 5 print my_int , type ( my_int ) my_float = 5.0 print my_float , type ( my_float ) my_boolean = False print my_boolean , type ( my_boolean ) my_string = 'hello' print my_string , type ( my_string ) Lists ¶ One useful data type is the list, which stores an ordered , mutable sequence of any data type , even mixed In [ ]: my_list = [ my_int , my_float , my_boolean , my_string ] print type ( my_list ) for element in my_list : print type ( element ) To retrieve or change specific elements in a list, indices and slicing can be used. Indexing starts at zero . Slices do not include the last element . In [ ]: print my_list [ 1 ] my_list [ 1 ] = 3.0 my_sublist = my_list [ 1 : 3 ] print my_sublist print type ( my_sublist ) Functions ¶ Re-usable pieces of code can be put into functions. Many pre-defined functions are available in Python packages. Functions can have both required and optional input arguments. When the function has no output argument, it returns None . In [ ]: # Function with a required and an optional argument def regress ( x , c = 0 , b = 1 ): return ( x * b ) + c print regress ( 5 ) # Only required argument print regress ( 5 , 10 , 3 ) # Use argument order print regress ( 5 , b = 3 ) # Specify the name to skip an optional argument In [ ]: # Function without return argument def divisible ( a , b ): if a % b : print str ( a ) + " is not divisible by " + str ( b ) else : print str ( a ) + " is divisible by " + str ( b ) divisible ( 9 , 3 ) res = divisible ( 9 , 2 ) print res In [ ]: # Function with multiple return arguments def add_diff ( a , b ): return a + b , a - b # Assigned as a tuple res = add_diff ( 5 , 3 ) print res # Directly unpacked to two variables a , d = add_diff ( 5 , 3 ) print a print d Objects ¶ Every variable in Python is actually an object. Objects bundle member variables with tightly connected member functions that (typically) use these member variables. Lists are a good example of this. In [ ]: my_list = [ 1 , False , 'boo' ] my_list . append ( 'extra element' ) my_list . remove ( False ) print my_list The member variables in this case just contain the information on the elements in the list. They are 'hidden' and not intended to be used directly - you manipulate the list through its member functions. The functions above are in-place methods, changing the original list directly, and returning None. This is not always the case. Some member functions, for instance in strings, do not modify the original object, but return a second, modified object instead. In [ ]: return_arg = my_list . append ( 'another one' ) print return_arg print my_list In [ ]: my_string = 'kumbaya, milord' return_arg = my_string . replace ( 'lord' , 'lard' ) print return_arg print my_string Do you remember why list functions are in-place, while string functions are not? Numpy ¶ Why we need Numpy ¶ While lists are great, they are not very suitable for scientific computing. Consider this example: In [ ]: subj_length = [ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ] subj_weight = [ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ] subj_bmi = [] # EXERCISE 1: Try to compute the BMI of each subject, as well as the average BMI across subjects # BMI = weight/(length/100)**2 Clearly, this is clumsy. MATLAB users would expect something like this to work: In [ ]: subj_bmi = subj_weight / ( subj_length / 100 ) ** 2 mean_bmi = mean ( subj_bmi ) But it doesn't. / and ** are not defined for lists; nor does the mean() function exist. + and * are defined, but they mean something else. Do you remember what they do? The ndarray data type ¶ Enter Numpy, and its ndarray data type, allowing these elementwise computations on ordered sequences, and implementing a host of mathematical functions operating on them. Lists are converted to Numpy arrays through calling the np.array() constructor function, which takes a list and creates a new array object filled with the list's values. In [ ]: import numpy as np # Create a numpy array from a list subj_length = np . array ([ 180.0 , 165.0 , 190.0 , 172.0 , 156.0 ]) subj_weight = np . array ([ 75.0 , 60.0 , 83.0 , 85.0 , 62.0 ]) print type ( subj_length ), type ( subj_weight ) # EXERCISE 2: Try to complete the program now! # Hint: np.mean() computes the mean of a numpy array # Note that unlike MATLAB, Python does not need the '.' before elementwise operators Numpy is a very large package, that we can't possibly cover completely. But we will cover enough to get you started. shape and dtype ¶ The most basic characteristics of a Numpy array are its shape and the data type of its elements, or dtype. For those of you who have worked in MATLAB before, this should be familiar. In [ ]: # Multi-dimensional lists are just nested lists # This is clumsy to work with my_nested_list = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] print my_nested_list print len ( my_nested_list ) print my_nested_list [ 0 ] print len ( my_nested_list [ 0 ]) In [ ]: # Numpy arrays handle multidimensionality better arr = np . array ( my_nested_list ) print arr # nicer printing print arr . shape # direct access to all dimension sizes print arr . size # direct access to the total number of elements print arr . ndim # direct access to the number of dimensions The member variables shape and size contain the dimension lengths and the total number of elements, respectively, while ndim contains the number of dimensions. The shape is represented by a tuple, where the last dimension is the inner dimension representing the columns of a 2-D matrix. The first dimension is the top-level, outer dimension and represents the rows here. We could also make 3-D (or even higher-level) arrays: In [ ]: arr3d = np . array ([ [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]] , [[ 7 , 8 , 9 ],[ 10 , 11 , 12 ]] ]) print arr3d print arr3d . shape print arr3d . size print arr3d . ndim Now the last or inner dimension becomes the layer dimension. The inner lists of the constructor represent the values at that (row,column) coordinate of the various layers. Rows and columns remain the first two dimensions. Note how what we have here now, is three layers of two-by-two matrices. Not two layers of two-by-three matrices. This implies that dimension sizes are listed from low to high in the shape tuple. The second basic property of an array is its dtype . Contrary to list elements, numpy array elements are (typically) all of the same type. In [ ]: # The type of a numpy array is always... numpy.ndarray arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) print type ( arr ) # So, let's do a computation print arr / 2 # Apparently we're doing our computations on integer elements! # How do we find out? print arr . dtype In [ ]: # And how do we fix this? arr = arr . astype ( 'float' ) # Note: this is not an in-place function! print arr . dtype print arr / 2 In [ ]: # Alternatively, we could have defined our dtype better from the start arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]], dtype = 'float' ) print arr . dtype arr = np . array ([[ 1. , 2. , 3. ],[ 4. , 5. , 6. ]]) print arr . dtype To summarize, any numpy array is of the data type numpy.ndarray , but the data type of its elements can be set separately as its dtype member variable. It's a good idea to explicitly define the dtype when you create the array. Indexing and slicing ¶ The same indexing and slicing operations used on lists can also be used on Numpy arrays. It is possible to perform computations on slices directly. But pay attention - Numpy arrays must have an identical shape if you want to combine them. There are some exceptions though, the most common being scalar operands. In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # Indexing and slicing print arr [ 0 , 0 ] # or: arr[0][0] print arr [: - 1 , 0 ] In [ ]: # Elementwise computations on slices # Remember, the LAST dimension is the INNER dimension print arr [:, 0 ] * arr [:, 1 ] print arr [ 0 ,:] * arr [ 1 ,:] # Note that you could never slice across rows like this in a nested list! In [ ]: # This doesn't work # print arr[1:,0] * arr[:,1] # And here's why: print arr [ 1 :, 0 ] . shape , arr [:, 1 ] . shape In [ ]: # This however does work. You can always use scalars as the other operand. print arr [:, 0 ] * arr [ 2 , 2 ] # Or, similarly: print arr [:, 0 ] * 9. As an exercise , can you create a 2x3 array containing the column-wise and the row-wise means of the original matrix, respectively? Without using a for-loop. In [ ]: # EXERCISE 3: Create a 2x3 array containing the column-wise and the row-wise means of the original matrix # Do not use a for-loop, and also do not use the np.mean() function for now. arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) This works, but it is still a bit clumsy. We will learn more efficient methods below. Filling and manipulating arrays ¶ Creating arrays mustn't always be done by hand. The following functions are particularly common. Again, they are analogous to what you do in MATLAB. In [ ]: # 1-D array, filled with zeros arr = np . zeros ( 3 ) print arr # Multidimensional array of a given shape, filled with ones # This automatically allows you to fill arrays with /any/ value arr = np . ones (( 3 , 2 )) * 5 print arr # Sequence from 1 to AND NOT including 16, in steps of 3 # Note that using a float input makes the dtype a float as well # This is equivalent to np.array(range(1.,16.,3)) arr = np . arange ( 1. , 16. , 3 ) print arr # Sequence from 1 to AND including 16, in 3 steps # This always returns an array with dtype float arr = np . linspace ( 1 , 16 , 3 ) print arr In [ ]: # Array of random numbers between 0 and 1, of a given shape # Note that the inputs here are separate integers, not a tuple arr = np . random . rand ( 5 , 2 ) print arr # Array of random integers from 0 to AND NOT including 10, of a given shape # Here the shape is defined as a tuple again arr = np . random . randint ( 0 , 10 ,( 5 , 2 )) print arr Once we have an array, we may wish to replicate it to create a larger array. Here the concept of an axis becomes important, i.e., along which of the dimensions of the array are you working? axis=0 corresponds to the first dimension of the shape tuple, axis=-1 always corresponds to the last dimension (inner dimension; columns in case of 2D, layers in case of 3D). In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) print arr0 # 'repeat' replicates elements along a given axis # Each element is replicated directly after itself arr = np . repeat ( arr0 , 3 , axis =- 1 ) print arr # We may even specify the number of times each element should be repeated # The length of the tuple should correspond to the dimension length arr = np . repeat ( arr0 , ( 2 , 4 ), axis = 0 ) print arr In [ ]: print arr0 # 'tile' replicates the array as a whole # Use a tuple to specify the number of tilings along each dimensions arr = np . tile ( arr0 , ( 2 , 4 )) print arr In [ ]: # 'meshgrid' is commonly used to create X and Y coordinate arrays from two vectors # where each array contains the X or Y coordinates corresponding to a given pixel in an image x = np . arange ( 10 ) y = np . arange ( 5 ) print x , y arrx , arry = np . meshgrid ( x , y ) print arrx print arry Concatenating an array allows you to make several arrays into one. In [ ]: arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # 'concatenate' requires an axis to perform its operation on # The original arrays should be put in a tuple arr = np . concatenate (( arr0 , arr1 ), axis = 0 ) print arr # as new rows arr = np . concatenate (( arr0 , arr1 ), axis = 1 ) print arr # as new columns In [ ]: # Suppose we want to create a 3-D matrix from them, # we have to create them as being three-dimensional # (what happens if you don't?) arr0 = np . array ([[[ 1 ],[ 2 ]],[[ 3 ],[ 4 ]]]) arr1 = np . array ([[[ 5 ],[ 6 ]],[[ 7 ],[ 8 ]]]) print arr0 . shape , arr1 . shape arr = np . concatenate (( arr0 , arr1 ), axis = 2 ) print arr In [ ]: # hstack, vstack, and dstack are short-hand functions # which will automatically create these 'missing' dimensions arr0 = np . array ([[ 1 , 2 ],[ 3 , 4 ]]) arr1 = np . array ([[ 5 , 6 ],[ 7 , 8 ]]) # vstack() concatenates rows arr = np . vstack (( arr0 , arr1 )) print arr # hstack() concatenates columns arr = np . hstack (( arr0 , arr1 )) print arr # dstack() concatenates 2D arrays into 3D arrays arr = np . dstack (( arr0 , arr1 )) print arr In [ ]: # Their counterparts are the hsplit, vsplit, dsplit functions # They take a second argument: how do you want to split arr = np . random . rand ( 4 , 4 ) print arr print '--' # Splitting int equal parts arr0 , arr1 = hsplit ( arr , 2 ) print arr0 print arr1 print '--' # Or, specify exact split points arr0 , arr1 , arr2 = hsplit ( arr ,( 1 , 2 )) print arr0 print arr1 print arr2 Finally, we can easily reshape and transpose arrays In [ ]: arr0 = np . arange ( 10 ) print arr0 print '--' # 'reshape' does exactly what you would expect # Make sure though that the total number of elements remains the same arr = np . reshape ( arr0 ,( 5 , 2 )) print arr # You can also leave one dimension blank by using -1 as a value # Numpy will then compute for you how long this dimension should be arr = np . reshape ( arr0 ,( - 1 , 5 )) print arr print '--' # 'transpose' allows you to switch around dimensions # A tuple specifies the new order of dimensions arr = np . transpose ( arr ,( 1 , 0 )) print arr # For simply transposing rows and columns, there is the short-hand form .T arr = arr . T print arr print '--' # 'flatten' creates a 1D array out of everything arr = arr . flatten () print arr Time for an exercise! Can you write your own 'meshgrid3d' function, which returns the resulting 2D arrays as two layers of a 3D matrix, instead of two separate 2D arrays? In [ ]: # EXERCISE 4: Create your own meshgrid3d function # Like np.meshgrid(), it should take two vectors and replicate them; one into columns, the other into rows # Unlike np.meshgrid(), it should return them as a single 3D array rather than 2D arrays # ...do not use the np.meshgrid() function def meshgrid3d ( xvec , yvec ): # fill in! xvec = np . arange ( 10 ) yvec = np . arange ( 5 ) xy = meshgrid3d ( xvec , yvec ) print xy print xy [:,:, 0 ] # = first output of np.meshgrid() print xy [:,:, 1 ] # = second output of np.meshgrid() A few useful functions ¶ We can now handle arrays in any way we like, but we still don't know any operations to perform on them, other than the basic arithmetic operations. Luckily numpy implements a large collection of common computations. This is a very short review of some useful functions. In [ ]: arr = np . random . rand ( 5 ) print arr # Sorting and shuffling res = arr . sort () print arr # in-place!!! print res res = np . random . shuffle ( arr ) print arr # in-place!!! print res In [ ]: # Min, max, mean, standard deviation arr = np . random . rand ( 5 ) print arr mn = np . min ( arr ) mx = np . max ( arr ) print mn , mx mu = np . mean ( arr ) sigma = np . std ( arr ) print mu , sigma In [ ]: # Some functions allow you to specify an axis to work along, in case of multidimensional arrays arr2d = np . random . rand ( 3 , 5 ) print arr2d print np . mean ( arr2d , axis = 0 ) print np . mean ( arr2d , axis = 1 ) In [ ]: # Trigonometric functions # Note: Numpy works with radians units, not degrees arr = np . random . rand ( 5 ) print arr sn = np . sin ( arr * 2 * np . pi ) cs = np . cos ( arr * 2 * np . pi ) print sn print cs In [ ]: # Exponents and logarithms arr = np . random . rand ( 5 ) print arr xp = np . exp ( arr ) print xp print np . log ( xp ) In [ ]: # Rounding arr = np . random . rand ( 5 ) print arr print arr * 5 print np . round ( arr * 5 ) print np . floor ( arr * 5 ) print np . ceil ( arr * 5 ) A complete list of all numpy functions can be found at the Numpy website . Or, a google search for 'numpy tangens', 'numpy median' or similar will usually get you there as well. A small exercise ¶ Remember how you were asked to create a 2x3 array containing the column-wise and the row-wise means of a matrix above? We now have the knowledge to do this far shorter. Use a concatenation function and a statistical function to obtain the same thing! In [ ]: # EXERCISE 5: Make a better version of Exercise 3 with what you've just learned arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]], dtype = 'float' ) # What we had: print np . array ([( arr [:, 0 ] + arr [:, 1 ] + arr [:, 2 ]) / 3 ,( arr [ 0 ,:] + arr [ 1 ,:] + arr [ 2 ,:]) / 3 ]) # Now the new version: A bit harder: The Gabor ¶ A Gabor patch is the product of a sinusoidal grating and a Gaussian. If we ignore orientation and just create a vertically oriented Gabor, the grating luminance (bounded between -1 and 1) is created by: $grating = \sin(xf)$ where $x$ is the $x$ coordinate of a pixel, and $f$ is the frequency of the sine wave (how many peaks per $2 \pi$ coordinate units). A simple 2D Gaussian luminance profile (bounded between 0 and 1) with its peak at coordinate $(0,0)$ and a variance of $1$ is given by: $gaussian = e^{-(x^2+y^2)/2}$ where $x$ and $y$ are again the $x$ and $y$ coordinates of a pixel. The Gabor luminance (bounded between -1 and 1) for any pixel then equals: $gabor = grating \times gaussian$ To visualize this, these are the grating, the Gaussian, and the Gabor, respectively (at maximal contrast): Now you try to create a 100x100 pixel image of a Gabor. Use $x$ and $y$ coordinate values ranging from $-\pi$ to $\pi$, and a frequency of 10 for a good-looking result. In [ ]: # EXERCISE 6: Create a Gabor patch of 100 by 100 pixels import numpy as np import matplotlib.pyplot as plt # Step 1: Define the 1D coordinate values # Tip: use 100 equally spaced values between -np.pi and np.pi # Step 2: Create the 2D x and y coordinate arrays # Tip: use np.meshgrid() # Step 3: Create the grating # Tip: Use a frequency of 10 # Step 4: Create the Gaussian # Tip: use np.exp() to compute a power of e # Step 5: Create the Gabor # Visualize your result # (we will discuss how this works later) plt . figure ( figsize = ( 15 , 5 )) plt . subplot ( 131 ) plt . imshow ( grating , cmap = 'gray' ) plt . subplot ( 132 ) plt . imshow ( gaussian , cmap = 'gray' ) plt . subplot ( 133 ) plt . imshow ( gabor , cmap = 'gray' ) plt . show () Boolean indexing ¶ The dtype of a Numpy array can also be boolean, that is, True or False . It is then particularly convenient that given an array of the same shape, these boolean arrays can be used to index other arrays . In [ ]: # Check whether each element of a 2x2 array is greater than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr > 0.5 print res print '--' # Analogously, check it against each element of a second 2x2 array arr2 = np . random . rand ( 2 , 2 ) print arr2 res = arr > arr2 print res In [ ]: # We can use these boolean arrays as indices into other arrays! # Add 0.5 to any element smaller than 0.5 arr = np . random . rand ( 2 , 2 ) print arr res = arr < 0.5 print res arr [ res ] = arr [ res ] + 0.5 print arr # Or, shorter: arr [ arr < 0.5 ] = arr [ arr < 0.5 ] + 0.5 # Or, even shorter: arr [ arr < 0.5 ] += 0.5 While it is possible to do multiplication and addition on boolean values (this will convert them to ones and zeros), the proper way of doing elementwise boolean logic is to use boolean operators : and, or, xor, not . In [ ]: arr = np . array ([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) # The short-hand forms for elementwise boolean operators are: & | ~ ^ # Use parentheses around such expressions res = ( arr < 4 ) & ( arr > 1 ) print res print '--' res = ( arr < 2 ) | ( arr == 5 ) print res print '--' res = ( arr > 3 ) & ~ ( arr == 6 ) print res print '--' res = ( arr > 3 ) ^ ( arr < 5 ) print res In [ ]: # To convert boolean indices to normal integer indices, use the 'nonzero' function print res print np . nonzero ( res ) print '--' # Separate row and column indices print np . nonzero ( res )[ 0 ] print np . nonzero ( res )[ 1 ] print '--' # Or stack and transpose them to get index pairs pairs = np . vstack ( np . nonzero ( res )) . T print pairs Vectorizing a simulation ¶ Numpy is excellent at making programs that involve iterative operations more efficient. This then requires you to re-imagine the problem as an array of values, rather than values that change with each loop iteration. For instance, imagine the following situation: You throw a die continuously until you either encounter the sequence ‘123’ or ‘111’. Which one can be expected to occur sooner? This could be proven mathematically, but in practice it is often faster to do a simulation instead of working out an analytical solution. We could just use two nested for-loops: In [ ]: import numpy as np # We will keep track of the sum of first occurence positions, # as well as the number of positions entered into this sum. # This way we can compute the mean. sum111 = 0. n111 = 0. sum123 = 0. n123 = 0. for sim in range ( 5000 ): # Keep track of how far along we are in finding a given pattern d111 = 0 d123 = 0 for throw in range ( 2000 ): # Throw a die die = np . random . randint ( 1 , 7 ) # 111 case if d111 == 3 : pass elif die == 1 and d111 == 0 : d111 = 1 elif die == 1 and d111 == 1 : d111 = 2 elif die == 1 and d111 == 2 : d111 = 3 sum111 = sum111 + throw n111 = n111 + 1 else : d111 = 0 # 123 case if d123 == 3 : pass elif die == 1 : d123 = 1 elif die == 2 and d123 == 1 : d123 = 2 elif die == 3 and d123 == 2 : d123 = 3 sum123 = sum123 + throw n123 = n123 + 1 else : d123 = 0 # Don't continue if both have been found if d111 == 3 and d123 == 3 : break # Compute the averages avg111 = sum111 / n111 avg123 = sum123 / n123 print avg111 , avg123 # ...can you spot the crucial difference between both patterns? However this is inefficient and makes the code unwieldy. Vectorized solutions are usually preferred. Try to run these 5000 simulations using Numpy, without any loops , and see whether the result is the same. Use a maximal die-roll sequence length of 2000, and just assume that both '123' and '111' will occur before the end of any sequence. You will have to make use of 2D arrays and boolean logic. A quick solution to find the first occurence in a boolean array is to use argmax - use the only Numpy documentation to find out how to use it. Vectorizing problems is a crucial skill in scientific computing! In [ ]: # EXERCISE 7: Vectorize the above program # You get these lines for free... import numpy as np throws = np . random . randint ( 1 , 7 ,( 5000 , 2000 )) one = ( throws == 1 ) two = ( throws == 2 ) three = ( throws == 3 ) # Find out where all the 111 and 123 sequences occur find111 = find123 = # Then at what index they /first/ occur in each sequence first111 = first123 = # Compute the average first occurence location for both situations avg111 = avg123 = # Print the result print avg111 , avg123 In this particular example, the nested for-loop solution does have the advantage that it can 'break' out of the die throwing sequence when first occurences of both patterns have been found, whereas Numpy will always generate complete sequences of 2000 rolls. Remove the break statement in the first solution to see what the speed difference would have been if both programs were truly doing the same thing! PIL: the Python Imaging Library ¶ As vision scientists, images are a natural stimulus to work with. The Python Imaging Library will help us handle images, similar to the Image Processing toolbox in MATLAB. Note that PIL itself has nowadays been superseded by Pillow , for which an excellent documentation can be found here . The module to import is however still called 'PIL'. In practice, we will mostly use its Image module. In [ ]: from PIL import Image Loading and showing images ¶ The image we will use for this example code should be in the same directory as this file. But really, any color image will do, as long as you put it in the same directory as this notebook, and change the filename string in the code to correspond with the actual image filename. In [ ]: # Opening an image is simple enough: # Construct an Image object with the filename as an argument im = Image . open ( 'python.jpg' ) # It is now represented as an object of the 'JpegImageFile' type print im # There are some useful member variables we can inspect here print im . format # format in which the file was saved print im . size # pixel dimensions print im . mode # luminance/color model used # We can even display it # NOTE this is not perfect; meant for debugging im . show () If the im.show() call does not work well on your system, use this function instead to show images in a separate window. Note, you must always close the window before you can continue using the notebook. ( Tkinter is a package to write graphical user interfaces in Python, we will not discuss it here) In [ ]: # Alternative quick-show method from Tkinter import Tk , Button from PIL import ImageTk def alt_show ( im ): win = Tk () tkimg = ImageTk . PhotoImage ( im ) Button ( image = tkimg ) . pack () win . mainloop () alt_show ( im ) Once we have opened the image in PIL, we can convert it to a Numpy object. In [ ]: # We can convert PIL images to an ndarray! arr = np . array ( im ) print arr . dtype # uint8 = unsigned 8-bit integer (values 0-255 only) print arr . shape # Why do we have three layers? # Let's make it a float-type for doing computations arr = arr . astype ( 'float' ) print arr . dtype # This opens up unlimited possibilities for image processing! # For instance, let's make this a grayscale image, and add white noise max_noise = 50 arr = np . mean ( arr , - 1 ) noise = ( np . random . rand ( arr . shape [ 0 ], arr . shape [ 1 ]) - 0.5 ) * 2 arr = arr + noise * max_noise # Make sure we don't exceed the 0-255 limits of a uint8 arr [ arr < 0 ] = 0 arr [ arr > 255 ] = 255 The conversion back to PIL is easy as well In [ ]: # When going back to PIL, it's a good idea to explicitly # specify the right dtype and the mode. # Because automatic conversions might mess things up arr = arr . astype ( 'uint8' ) imn = Image . fromarray ( arr , mode = 'L' ) print imn . format print imn . size print imn . mode # L = greyscale imn . show () # or use alt_show() from above if show() doesn't work well for you # Note that /any/ 2D or 2Dx3 numpy array filled with values between 0 and 255 # can be converted to an image object in this way Resizing, rotating, cropping and converting ¶ The main operations of the PIL Image module you will probably use, are its resizing and conversion capabilities. In [ ]: im = Image . open ( 'python.jpg' ) # Make the image smaller ims = im . resize (( 800 , 600 )) ims . show () # Or you could even make it larger # The resample argument allows you to specify the method used iml = im . resize (( 1280 , 1024 ), resample = Image . BILINEAR ) iml . show () In [ ]: # Rotation is similar (unit=degrees) imr = im . rotate ( 10 , resample = Image . BILINEAR , expand = False ) imr . show () # If we want to lose the black corners, we can crop (unit=pixels) imr = imr . crop (( 100 , 100 , 924 , 668 )) imr . show () In [ ]: # 'convert' allows conversion between different color models # The most important here is between 'L' (luminance) and 'RGB' (color) imbw = im . convert ( 'L' ) imbw . show () print imbw . mode imrgb = imbw . convert ( 'RGB' ) imrgb . show () print imrgb . mode # Note that the grayscale conversion of PIL is more sophisticated # than simply averaging the three layers in Numpy (it is a weighted average) # Also note that the color information is effectively lost after converting to L Advanced ¶ The ImageFilter module implements several types of filters to execute on any image. You can also define your own. In [ ]: from PIL import Image , ImageFilter im = Image . open ( 'python.jpg' ) imbw = im . convert ( 'L' ) # Contour detection filter imf = imbw . filter ( ImageFilter . CONTOUR ) imf . show () # Blurring filter imf = imbw . filter ( ImageFilter . GaussianBlur ( radius = 3 )) imf . show () Similarly, you can import the ImageDraw module to draw shapes and text onto an image. In [ ]: from PIL import Image , ImageDraw im = Image . open ( 'python.jpg' ) # You need to attach a drawing object to the image first imd = ImageDraw . Draw ( im ) # Then you work on this object imd . rectangle ([ 10 , 10 , 100 , 100 ], fill = ( 255 , 0 , 0 )) imd . line ([( 200 , 200 ),( 200 , 600 )], width = 10 , fill = ( 0 , 0 , 255 )) imd . text ([ 500 , 500 ], 'Python' , fill = ( 0 , 255 , 0 )) # The results are automatically applied to the Image object im . show () Saving ¶ Finally, you can of course save these image objects back to a file on the disk. In [ ]: # PIL will figure out the file type by the extension im . save ( 'python.bmp' ) # There are also further options, like compression quality (0-100) im . save ( 'python_bad.jpg' , quality = 5 ) Exercise ¶ We mentioned that the conversion to grayscale in PIL is not just a simple averaging of the RGB layers. Can you visualize as an image what the difference in result looks like, when comparing a simple averaging to a PIL grayscale conversion? Pixels that are less luminant in the plain averaging method should be displayed in red, with a luminance depending on the size of the difference. Pixels that are more luminant when averaging in Numpy should similarly be displayed in green. Hint: you will have to make use of Boolean indexing. As an extra, try to maximize the contrast in your image, so that all values from 0-255 are used. As a second extra, save the result as PNG files of three different sizes (large, medium, small), at respectively the full image resolution, half of the image size, and a quarter of the image size. In [ ]: # EXERCISE 8: Visualize the difference between the PIL conversion to grayscale, and a simple averaging of RGB # Display pixels where the average is LESS luminant in red, and where it is MORE luminant in shades green # The luminance of these colors should correspond to the size of the difference # # Extra 1: Maximize the overall contrast in your image # # Extra 2: Save as three PNG files, of different sizes (large, medium, small) Matplotlib ¶ While PIL is useful for processing photographic images, it falls short for creating data plots and other kinds of schematic figures. Matplotlib offers a far more advanced solution for this, specifically through its pyplot module. Quick plots ¶ Common figures such as scatter plots, histograms and barcharts can be generated and manipulated very simply. In [ ]: import numpy as np from PIL import Image import matplotlib.pyplot as plt # As data for our plots, we will use the pixel values of the image # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () In [ ]: # QUICKPLOT 1: Correlation of luminances in the image # This works if you want to be very quick: # (xb means blue crosses, .g are green dots) plt . plot ( R , B , 'xb' ) plt . plot ( R , G , '.g' ) In [ ]: # However we will take a slightly more disciplined approach here # Note that Matplotlib wants colors expressed as 0-1 values instead of 0-255 # Create a square figure plt . figure ( figsize = ( 5 , 5 )) # Plot both scatter clouds # marker: self-explanatory # linestyle: 'None' because we want no line # color: RGB triplet with values 0-1 plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Make the axis scales equal, and name them plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Show the result plt . show () In [ ]: # QUICKPLOT 2: Histogram of 'red' values in the image plt . hist ( R ) In [ ]: # ...and now a nicer version # Make a non-square figure plt . figure ( figsize = ( 7 , 5 )) # Make a histogram with 25 red bins # Here we simply use the abbreviation 'r' for red plt . hist ( R , bins = 25 , color = 'r' ) # Set the X axis limits and label plt . xlim ([ 0 , 255 ]) plt . xlabel ( 'Red value' , size = 16 ) # Remove the Y ticks and labels by setting them to an empty list plt . yticks ([]) # Remove the top ticks by specifying the 'top' argument plt . tick_params ( top = False ) # Add two vertical lines for the mean and the median plt . axvline ( np . mean ( R ), color = 'g' , linewidth = 3 , label = 'mean' ) plt . axvline ( np . median ( R ), color = 'b' , linewidth = 1 , linestyle = ':' , label = 'median' ) # Generate a legend based on the label= arguments plt . legend ( loc = 2 ) # Show the plot plt . show () In [ ]: # QUICKPLOT 3: Bar chart of mean+std of RGB values plt . bar ([ 0 , 1 , 2 ],[ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )]) In [ ]: # ...and now a nicer version # Make a non-square-figure plt . figure ( figsize = ( 7 , 5 )) # Plot the bars with various options # x location where bars start, y height of bars # yerr: data for error bars # width: width of the bars # color: surface color of bars # ecolor: color of error bars ('k' means black) plt . bar ([ 0 , 1 , 2 ], [ np . mean ( R ), np . mean ( G ), np . mean ( B )], yerr = [ np . std ( R ), np . std ( G ), np . std ( B )], width = 0.75 , color = [ 'r' , 'g' , 'b' ], ecolor = 'k' ) # Set the X-axis limits and tick labels plt . xlim (( - 0.25 , 3. )) plt . xticks ( np . array ([ 0 , 1 , 2 ]) + 0.75 / 2 , [ 'Red' , 'Green' , 'Blue' ], size = 16 ) # Remove all X-axis ticks by setting their length to 0 plt . tick_params ( length = 0 ) # Set a figure title plt . title ( 'RGB Color Channels' , size = 16 ) # Show the figure plt . show () A full documentation of all these pyplot commands and options can be found here . If you use Matplotlib, you will be consulting this page a lot! Saving to a file ¶ Saving to a file is easy enough, using the savefig() function. However, there are some caveats, depending on the exact environment you are using. You have to use it BEFORE calling plt.show() and, in case of this notebook, within the same codebox. The reason for this is that Matplotlib is automatically deciding for you which plot commands belong to the same figure based on these criteria. In [ ]: # So, copy-paste this line into the box above, before the plt.show() command plt . savefig ( 'bar.png' ) # There are some further formatting options possible, e.g. plt . savefig ( 'bar.svg' , dpi = 300 , bbox_inches = ( 'tight' ), pad_inches = ( 1 , 1 ), facecolor = ( 0.8 , 0.8 , 0.8 )) Visualizing arrays ¶ Like PIL, Matplotlib is capable of displaying the contents of 2D Numpy arrays. The primary method is imshow() In [ ]: # A simple grayscale luminance map # cmap: colormap used to display the values plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ), cmap = 'gray' ) plt . show () # Importantly and contrary to PIL, imshow luminances are by default relative # That is, the values are always rescaled to 0-255 first (maximum contrast) # Moreover, colormaps other than grayscale can be used plt . figure ( figsize = ( 5 , 5 )) plt . imshow ( np . mean ( arr , 2 ) + 100 , cmap = 'jet' ) # or hot, hsv, cool,... plt . show () # as you can see, adding 100 didn't make a difference here Multi-panel figures ¶ As we noted, Matplotlib is behind the scenes keeping track of what your current figure is. This is often convenient, but in some cases you want to keep explicit control of what figure you're working on. For this, we will have to make a distinction between Figure and Axes objects. In [ ]: # 'Figure' objects are returned by the plt.figure() command fig = plt . figure ( figsize = ( 7 , 5 )) print type ( fig ) # Axes objects are the /actual/ plots within the figure # Create them using the add_axes() method of the figure object # The input coordinates are relative (left, bottom, width, height) ax0 = fig . add_axes ([ 0.1 , 0.1 , 0.4 , 0.7 ], xlabel = 'The X Axis' ) ax1 = fig . add_axes ([ 0.2 , 0.2 , 0.5 , 0.2 ], axisbg = 'gray' ) ax2 = fig . add_axes ([ 0.4 , 0.5 , 0.4 , 0.4 ], projection = 'polar' ) print type ( ax0 ), type ( ax1 ), type ( ax2 ) # This allows you to execute functions like savefig() directly on the figure object # This resolves Matplotlib's confusion of what the current figure is, when using plt.savefig() fig . savefig ( 'fig.png' ) # It also allows you to add text to the figure as a whole, across the different axes objects fig . text ( 0.5 , 0.5 , 'splatter' , color = 'r' ) # The overall figure title can be set separate from the individual plot titles fig . suptitle ( 'What a mess' , size = 18 ) # show() is actually a figure method as well # It just gets 'forwarded' to what is thought to be the current figure if you use plt.show() fig . show () For a full list of the Figure methods and options, go here . In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 10 )) # As we saw, many of the axes properties can already be set at their creation ax0 = fig . add_axes ([ 0. , 0. , 0.25 , 0.25 ], xticks = ( 0.1 , 0.5 , 0.9 ), xticklabels = ( 'one' , 'thro' , 'twee' )) ax1 = fig . add_axes ([ 0.3 , 0. , 0.25 , 0.25 ], xscale = 'log' , ylim = ( 0 , 0.5 )) ax2 = fig . add_axes ([ 0.6 , 0. , 0.25 , 0.25 ]) # Once you have the axes object though, there are further methods available # This includes many of the top-level pyplot functions # If you use for instance plt.plot(), Matplotlib is actually 'forwarding' this # to an Axes.plot() call on the current Axes object R . sort () G . sort () B . sort () ax2 . plot ( R , color = 'r' , linestyle = '-' , marker = 'None' ) # plot directly to an Axes object of choice plt . plot ( G , color = 'g' , linestyle = '-' , marker = 'None' ) # plt.plot() just plots to the last created Axes object ax2 . plot ( B , color = 'b' , linestyle = '-' , marker = 'None' ) # Other top-level pyplot functions are simply renamed to 'set_' functions here ax1 . set_xticks ([]) plt . yticks ([]) # Show the figure fig . show () The full methods and options of Axes can be found here . Clearly, when making a multi-panel figure, we are actually creating a single Figure object with multiple Axes objects attached to it. Having to set the Axes sizes manually is annoying though. Luckily, the subplot() method can handle much of this automatically. In [ ]: # Create a new figure fig = plt . figure ( figsize = ( 15 , 5 )) # Specify the LAYOUT of the subplots (rows,columns) # as well as the CURRENT Axes you want to work on ax0 = fig . add_subplot ( 231 ) # Equivalent top-level call on the current figure # It is also possible to create several subplots at once using plt.subplots() ax1 = plt . subplot ( 232 ) # Optional arguments are similar to those of add_axes() ax2 = fig . add_subplot ( 233 , title = 'three' ) # We can use these Axes object as before ax3 = fig . add_subplot ( 234 ) ax3 . plot ( R , 'r-' ) ax3 . set_xticks ([]) ax3 . set_yticks ([]) # We skipped the fifth subplot, and create only the 6th ax5 = fig . add_subplot ( 236 , projection = 'polar' ) # We can adjust the spacings afterwards fig . subplots_adjust ( hspace = 0.4 ) # And even make room in the figure for a plot that doesn't fit the grid fig . subplots_adjust ( right = 0.5 ) ax6 = fig . add_axes ([ 0.55 , 0.1 , 0.3 , 0.8 ]) # Show the figure fig . show () Exercise: Function plots ¶ Create a figure with a 2:1 aspect ratio, containing two subplots, one above the other. The TOP figure should plot one full cycle of a sine wave, that is $y=sin(x)$. Use $0$ to $2\pi$ as values on the X axis. On the same scale, the BOTTOM figure should plot $y=sin(x^2)$ instead. Tweak your figure until you think it looks good. In [ ]: # EXERCISE 9: Plot y=sin(x) and y=sin(x^2) in two separate subplots, one above the other # Let x range from 0 to 2*pi Finer figure control ¶ If you are not satisfied with the output of these general plotting functions, despite all the options they offer, you can start fiddling with the details manually. First, many figure elements can be manually added through top-level or Axes functions: In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Add horizontal lines ax0 . axhline ( 0 , color = 'g' ) ax0 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax0 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( 0 , color = 'g' ) ax1 . axhline ( 0.5 , color = 'gray' , linestyle = ':' ) ax1 . axhline ( - 0.5 , color = 'gray' , linestyle = ':' ) # Add text to the plots ax0 . text ( 0.1 , - 0.9 , '$y = sin(x)$' , size = 16 ) # math mode for proper formula formatting! ax1 . text ( 0.1 , - 0.9 , '$y = sin(x^2)$' , size = 16 ) # Annotate certain points with a value for x_an in np . linspace ( 0 , 2 * np . pi , 9 ): ax0 . annotate ( str ( round ( sin ( x_an ), 2 )),( x_an , sin ( x_an ))) # Add an arrow (x,y,xlength,ylength) ax0 . arrow ( np . pi - 0.5 , - 0.5 , 0.5 , 0.5 , head_width = 0.1 , length_includes_head = True ) Second, all basic elements like lines, polygons and the individual axis lines are customizable objects in their own right , attached to a specific Axes object. They can be retrieved, manipulated, created from scratch, and added to existing Axes objects. In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # For instance, fetch the X axis # XAxis objects have their own methods xax = ax1 . get_xaxis () print type ( xax ) # These methods allow you to fetch the even smaller building blocks # For instance, tick-lines are Line2D objects attached to the XAxis xaxt = xax . get_majorticklines () print len ( xaxt ) # Of which you can fetch AND change the properties # Here we change just one tickline into a cross print xaxt [ 6 ] . get_color () xaxt [ 6 ] . set_color ( 'g' ) xaxt [ 6 ] . set_marker ( 'x' ) xaxt [ 6 ] . set_markersize ( 10 ) In [ ]: # This uses the result of the exercise above # You have to copy-paste it into the same code-box, before the fig.show() # Another example: fetch the lines in the plot # Change the color, change the marker, and mark only every 100 points for one specific line ln = ax0 . get_lines () print ln ln [ 0 ] . set_color ( 'g' ) ln [ 0 ] . set_marker ( 'o' ) ln [ 0 ] . set_markerfacecolor ( 'b' ) ln [ 0 ] . set_markevery ( 100 ) # Finally, let's create a graphic element from scratch, that is not available as a top-level pyplot function # And then attach it to existing Axes # NOTE: we need to import something before we can create the ellipse like this. What should we import? ell = matplotlib . patches . Ellipse (( np . pi , 0 ), 1. , 1. , color = 'r' ) ax0 . add_artist ( ell ) ell . set_hatch ( '//' ) ell . set_edgecolor ( 'black' ) ell . set_facecolor (( 0.9 , 0.9 , 0.9 )) Exercise: Add regression lines ¶ Take the scatterplot from the first example, and manually add a regression line to both the R-G and the R-B comparisons. Try not to use the plot() function for the regression line, but manually create a Line2D object instead, and attach it to the Axes. Useful functions: np.polyfit(x,y,1) performs a linear regression, returning slope and constant plt.gca() retrieves the current Axes object matplotlib.lines.Line2D(x,y) can create a new Line2D object from x and y coordinate vectors In [ ]: # EXERCISE 10: Add regression lines import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.lines as lines # Open image, convert to an array im = Image . open ( 'python.jpg' ) im = im . resize (( 400 , 300 )) arr = np . array ( im , dtype = 'float' ) # Split the RGB layers and flatten them R , G , B = np . dsplit ( arr , 3 ) R = R . flatten () G = G . flatten () B = B . flatten () # Do the plotting plt . figure ( figsize = ( 5 , 5 )) plt . plot ( R , B , marker = 'x' , linestyle = 'None' , color = ( 0 , 0 , 0.6 )) plt . plot ( R , G , marker = '.' , linestyle = 'None' , color = ( 0 , 0.35 , 0 )) # Tweak the plot plt . axis ([ 0 , 255 , 0 , 255 ]) plt . xlabel ( 'Red value' ) plt . ylabel ( 'Green/Blue value' ) # Fill in your code... # Show the result plt . show () Scipy ¶ Scipy is a large library of scientific functions, covering for instance numerical integration, linear algebra, Fourier transforms, and interpolation algorithms. If you can't find the equivalent of your favorite MATLAB function in any of the previous three packages, Scipy is a good place to look. A full list of all submodules can be found here . We will pick two useful modules from SciPy: stats and fftpack I will not give a lot of explanation here. I'll leave it up to you to navigate through the documentation, and find out how these functions work. Statistics ¶ In [ ]: import numpy as np import scipy.stats as stats # Generate random numbers between 0 and 1 data = np . random . rand ( 30 ) # Do a t-test with a H0 for the mean of 0.4 t , p = stats . ttest_1samp ( data , 0.4 ) print p # Generate another sample of random numbers, with mean 0.4 data2 = np . random . rand ( 30 ) - 0.1 # Do a t-test that these have the same mean t , p = stats . ttest_ind ( data , data2 ) print p In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Simulate the size of the F statistic when comparing three conditions # Given a constant n, and an increasing true effect size. true_effect = np . linspace ( 0 , 0.5 , 500 ) n = 100 Fres = [] # Draw random normally distributed samples for each condition, and do a one-way ANOVA for eff in true_effect : c1 = stats . norm . rvs ( 0 , 1 , size = n ) c2 = stats . norm . rvs ( eff , 1 , size = n ) c3 = stats . norm . rvs ( 2 * eff , 1 , size = n ) F , p = stats . f_oneway ( c1 , c2 , c3 ) Fres . append ( F ) # Create the plot plt . figure () plt . plot ( true_effect , Fres , 'r*-' ) plt . xlabel ( 'True Effect' ) plt . ylabel ( 'F' ) plt . show () In [ ]: import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # Compute the pdf and cdf of normal distributions, with increasing sd's # Then plot them in different colors # (of course, many other distributions are also available) x = np . linspace ( - 5 , 5 , 1000 ) sds = np . linspace ( 0.25 , 2.5 , 10 ) cols = np . linspace ( 0.15 , 0.85 , 10 ) # Create the figure fig = plt . figure ( figsize = ( 10 , 5 )) ax0 = fig . add_subplot ( 121 ) ax1 = fig . add_subplot ( 122 ) # Compute the densities, and plot them for i , sd in enumerate ( sds ): y1 = stats . norm . pdf ( x , 0 , sd ) y2 = stats . norm . cdf ( x , 0 , sd ) ax0 . plot ( x , y1 , color = cols [ i ] * np . array ([ 1 , 0 , 0 ])) ax1 . plot ( x , y2 , color = cols [ i ] * np . array ([ 0 , 1 , 0 ])) # Show the figure plt . show () The stats module of SciPy contains more statistical distributions and further tests such as a Kruskall-Wallis test, Wilcoxon test, a Chi-Square test, a test for normality, and so forth. A full listing of functions is found here . For serious statistical models however, you should be looking at the statsmodels package, or the rpy interfacing package, allowing R to be called from within Python. Fast Fourier Transform ¶ FFT is commonly used to process or analyze images (as well as sound). Numpy has a FFT package, numpy.fft , but SciPy has its own set of functions as well in scipy.fftpack . Both are very similar, you can use whichever package you like. I will assume that you are familiar with the basic underlying theory. That is, that any periodic function can be described as a sum of sine-waves of different frequencies, amplitudes and phases. A Fast Fourier Transform allows you to do this very quickly for equally spaced samples from the function, returning a finite set of sinusoidal components with n equal to the number of samples, ordered by frequency. Let's do this for a simple 1D function. In [ ]: import numpy as np import scipy.fftpack as fft # The original data: a step function data = np . zeros ( 200 , dtype = 'float' ) data [ 25 : 100 ] = 1 # Decompose into sinusoidal components # The result is a series of complex numbers as long as the data itself res = fft . fft ( data ) # FREQUENCY is implied by the ordering, but can be retrieved as well # It increases from 0 to the Nyquist frequency (0.5), followed by its reversed negative counterpart # Note: in case of real input data, the FFT results will be | 2026-01-13T09:30:39 |
https://pages.awscloud.com/solutions/?nc2=h_ql_sol | AWS Support and Customer Service Contact Info | Amazon Web Services Skip to main content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Support › Contact AWS Contact AWS General support for sales, compliance, and subscribers Want to speak with an AWS sales specialist? Get in touch Chat online or talk by phone Connect with support directly Monday through Friday Request form Request AWS sales support Submit a sales support form Compliance support Request support related to AWS compliance Connect with AWS compliance support Subscriber support services Technical support Support for service related technical issues. Unavailable under the Basic Support Plan. Sign in and submit request Account or billing support Assistance with account and billing related inquiries Sign in to request Wrongful charges support Received a bill for AWS, but don't have an AWS account? Learn more Support plans Learn about AWS support plan options See Premium Support options AWS sign-in resources See additional resources for issues related to logging into the console Help signing in to the console Need assistance to sign in to the AWS Management Console? View documentation Trouble shoot your sign-in issue Tried sign in, but the credentials didn’t work? Or don’t have the credentials to access AWS root user account? View solutions Help with multi-factor authentication (MFA) issues Lost or unusable Multi-Factor Authentication (MFA) device View solution Still unable to sign in to your AWS account? If you are still unable to log into your AWS account please fill out this form. View form Additional resources Self-service re:Post provides access to curated knowledge and a vibrant community that helps you become even more successful on AWS View AWS re:Post Service limit increases Need to increase to service limit? Fill out a quick request form Sign in to request Report abuse Report abusive activity from Amazon Web Services Resources Report suspected abuse Amazon.com support Request Kindle or Amazon.com support View on amazon.com Did you find what you were looking for today? Let us know so we can improve the quality of the content on our pages Yes No Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms Cookie Preferences © 2026, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:30:39 |
https://aws.amazon.com/blogs/networking-and-content-delivery/snap-inc-uses-amazon-cloudfront-origin-shield-to-improve-download-and-upload-latency/#aws-page-content-main | Snap Inc. uses Amazon CloudFront Origin Shield to improve download and upload latency | Networking & Content Delivery Skip to Main Content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Blogs Home Blogs Editions Networking & Content Delivery Snap Inc. uses Amazon CloudFront Origin Shield to improve download and upload latency by Delyan Radichkov on 25 NOV 2025 in Amazon CloudFront , Amazon Simple Storage Service (S3) , Customer Solutions , Direct-to-Consumer & Streaming , Media & Entertainment , Networking & Content Delivery Permalink Share This blog was co-authored by Manchun Yao, Staff Software Engineer at Snap Inc. Snapchat is a popular app used by hundreds of millions of people around the world to communicate with their close friends and family. Snapchat’s focus is on enabling a fast and fun way to communicate by building features such as augmented reality (AR) Lenses, Maps, Bitmoji and Spotlight. The content is primarily visual, such as photos and short videos, often enhanced with AR effects and filters. This post explains how Snapchat used Amazon CloudFront and CloudFront Origin Shield to improve both download and upload experiences for users located farther away from the Amazon S3 content origins. CloudFront is the AWS content delivery network (CDN) service that securely delivers data, images, video, and APIs for your applications globally with low latency and high transfer speeds. CloudFront uses edge locations (also known as points of presence (PoPs)) to cache and deliver content closer to end users around the world. CloudFront Regional Edge Caches (RECs) provide another layer of caching between the CloudFront PoPs and your origin servers. This helps improve performance for content that isn’t accessed frequently enough to remain in an edge location. CloudFront Origin Shield is another caching layer hosted on Amazon Elastic Compute Cloud (Amazon EC2) that helps minimize origin load, improve availability, and reduce operating costs by consolidating multiple cache requests into a single origin request. With just a few clicks, Snap created a high performance solution that needed zero coding. Snap enabled CloudFront Origin Shield, which improved the download and upload performance by reducing upload latency by up to 30% and cache-miss download latency by up to 15%. This implementation further optimized the cache hit ratio and reduced the number of requests to the origin. Enhanced origin protection with CloudFront Origin Shield on top of REC To serve popular content quickly to your users, CloudFront uses PoPs. When the content is not popular enough to stay at a PoP, CloudFront uses REC to help improve the regional aggregation for that content. REC is a caching layer that is generally closer to the PoPs. RECs are located in AWS Regions across multiple Availability Zones (AZs). CloudFront Origin Shield is a service built on REC, but it is usually configured to be closer to your origin and its purpose is to provide global content aggregation. CloudFront Origin Shield is designed to complement REC in the CloudFront architecture. CloudFront Origin Shield provides another caching layer between the REC and your content origin. Furthermore, CloudFront Origin Shield reduces the number of requests to the origin through request collapsing, a technique that combines multiple identical requests for the same resource into a single request. The opening, closing, or maintaining of TCP connections between the edge and the origin is generally considered a resource and time-consuming mechanism. Instead of opening, maintaining, and closing a new TCP connection for each request to the origin, CloudFront Origin Shield uses persistent connections to the origin, which in Snap’s case is Amazon S3. This reduction in load translates to decreased costs and improved availability for your origin. As a general best practice, you should always choose the CloudFront Origin Shield Region that is closest to your origin. To improve the performance of your CDN, CloudFront Origin Shield creates a centralized caching layer that acts as a proxy to the origin. When multiple requests for the same content arrive simultaneously from different AWS Regions, Origin Shield consolidates them into as few as one request to the origin, using a technique called request collapsing. Moreover, CloudFront Origin Shield helps reduce the overall request latency by having lower round-trip time (RTT) for establishing new connections. It also helps improve the overall connection reuse rate toward origins by maintaining persistent connections. Connection reuse improves the connection setup, because it reduces the number of round trips, and it leads to faster performance. CloudFront Origin Shield helps reduce latency by reusing the same TCP connection for multiple requests. The following diagram depicts users requesting content from a PoP in an edge location in Sydney with the content origin in Amazon S3 in the Frankfurt Region. If the content is not cached at the PoP, then CloudFront routes the request to the CloudFront Origin Shield closest to the content origin using the high-throughput AWS Global Network , as shown in the following figure. Figure 1: Accessing content origin in another region using Origin Shield Snap’s requirements for choosing CloudFront Origin Shield Snap enabled Origin Shield to deliver two key outcomes: 1. Improve the network performance for both download and upload. 2. Maintain high availability, because CloudFront Origin Shield spans multiple AZs within AWS Regions . Snap implemented CloudFront Origin Shield for multiple benefits Snap first enabled CloudFront Origin Shield in the US East (N. Virginia) Region. The positive effect was almost immediate, especially for Snapchat users located farther away from the Amazon S3 origin. The implementation reduced upload latency by up to 30%. Additionally, it decreased cache-miss download latency by up to 15%. The performance improvements were the direct result of the reduced number of round trips due to connection reuse and from the network traffic remaining on the low latency AWS Global Network. Figure 2. A sample of reduced Time-To-First-Byte (TTFB) P50 latency for uploads from users located in Colombia Snap used CloudFront Origin Shield to improve content delivery speeds for its global users while reducing load on its Amazon S3 storage infrastructure. “CloudFront Origin Shield gave us an almost instantaneous, zero code, and very cost-effective way to improve both upload and download performance for users that are farther away from the content origin. We were able to improve the CloudFront cache-miss P50 latency performance by up to 15% for download and in some cases up to 30% for upload without having to redesign or make any architectural changes” said Mingkui Liu, Sr. Manager at Snap. Solution set up Snap began the CloudFront Origin Shield deployment by enabling the feature in the N. Virginia Region, which is closest to the Amazon S3 origin in the same Region. By default, CloudFront Origin Shield is disabled for CloudFront Origins. To enable CloudFront Origin Shield, proceed with the following steps: Step 1: Enable Origin Shield. In the CloudFront console, choose Edit or Create Distribution , then choose Yes . Step 2: Choose Origin Shield Region. Under the Origin Shield Region dropdown menu, choose the AWS Region. Always choose the AWS Region that is closest to your origin for the optimal performance. For the purposes of this example, we choose US East (N. Virginia) as the AWS Region for CloudFront Origin Shield to be the same as the Region of the S3 bucket, as shown in the following figure. Figure 3: Enabling CloudFront Origin Shield in the AWS console Summary CloudFront Origin Shield can improve the performance of your CloudFront distribution, especially for clients that are located farther away from the content origin. With just a few clicks, you can create a highly effective solution that needs zero coding and zero design and architectural changes. For the pricing details of Amazon CloudFront Origin Shield, see the CloudFront pricing . For information on how to estimate the monthly cost of CloudFront Origin Shield, see the CloudFront Developer Guide . Other charges may apply. CloudFront Origin Shield can improve the performance of your CloudFront distribution, especially for clients that are located farther away from the content origin. With just a few clicks, you can create a highly effective solution that needs zero coding and zero design and architectural changes. Origin Shield is included at no added cost in the CloudFront Premium flat-rate pricing plan . It’s also available on CloudFront pay-as-you-go pricing . For information on how to estimate the monthly cost of CloudFront Origin Shield with pay-as-you-go pricing, see the CloudFront Developer Guide . Other charges may apply. Additional resources If you want to learn more about CloudFront Origin Shield, check out these resources: Using CloudFront Origin Shield to protect your origin in a multi-CDN deployment Using Amazon CloudFront Origin Shield How CloudFront delivers content Amazon CloudFront pricing Delyan Radichkov Delyan is a Sr. Technical Account Manager at AWS. He has over 25 years of experience working in information technology. Since joining AWS in 2015, Delyan has specialized in guiding enterprise-scale customers through complex cloud transformations, helping them optimize their AWS infrastructure strategy and maximize business value. Resources Networking Products Getting Started Amazon CloudFront Follow Twitter Facebook LinkedIn Twitch Email Updates Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms Cookie Preferences © 2025, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classuint64__t.html | LLVM: uint64_t Class Reference LLVM  22.0.0git uint64_t Class Reference Detailed Description Examples /work/as-worker-4/publish-doxygen-docs/llvm-project/llvm/include/llvm/Transforms/Utils/Local.h . The documentation for this class was generated from the following files: Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classBitIntType-members.html | LLVM: Member List LLVM  22.0.0git BitIntType Member List This is the complete list of members for BitIntType , including all inherited members. ArrayCache Node protected BitIntType (const Node *Size_, bool Signed_) BitIntType inline Cache enum name Node dump () const Node FunctionCache Node protected getArrayCache () const Node inline getBaseName () const Node inline virtual getFunctionCache () const Node inline getKind () const Node inline getPrecedence () const Node inline getRHSComponentCache () const Node inline getSyntaxNode (OutputBuffer &) const Node inline virtual hasArray (OutputBuffer &OB) const Node inline hasArraySlow (OutputBuffer &) const Node inline virtual hasFunction (OutputBuffer &OB) const Node inline hasFunctionSlow (OutputBuffer &) const Node inline virtual hasRHSComponent (OutputBuffer &OB) const Node inline hasRHSComponentSlow (OutputBuffer &) const Node inline virtual Kind enum name Node match (Fn F) const BitIntType inline Node (Kind K_, Prec Precedence_=Prec::Primary, Cache RHSComponentCache_=Cache::No, Cache ArrayCache_=Cache::No, Cache FunctionCache_=Cache::No) Node inline Node (Kind K_, Cache RHSComponentCache_, Cache ArrayCache_=Cache::No, Cache FunctionCache_=Cache::No) Node inline Prec enum name Node print (OutputBuffer &OB) const Node inline printAsOperand (OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const Node inline printInitListAsType (OutputBuffer &, const NodeArray &) const Node inline virtual printLeft (OutputBuffer &OB) const override BitIntType inline virtual RHSComponentCache Node protected visit (Fn F) const Node ~Node ()=default Node virtual Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classNodeArray.html#a3d4239527b101b69019240315af54015 | LLVM: NodeArray Class Reference LLVM  22.0.0git Public Member Functions | List of all members NodeArray Class Reference #include " llvm/Demangle/ItaniumDemangle.h " Public Member Functions   NodeArray ()   NodeArray ( Node **Elements_, size_t NumElements_) bool   empty () const size_t  size () const Node **  begin () const Node **  end () const Node *  operator[] (size_t Idx) const void  printWithComma ( OutputBuffer &OB) const bool   printAsString ( OutputBuffer &OB) const Detailed Description Definition at line 327 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  NodeArray() [1/2] NodeArray::NodeArray ( ) inline Definition at line 332 of file ItaniumDemangle.h . ◆  NodeArray() [2/2] NodeArray::NodeArray ( Node ** Elements_ , size_t NumElements_  ) inline Definition at line 333 of file ItaniumDemangle.h . Member Function Documentation ◆  begin() Node ** NodeArray::begin ( ) const inline Definition at line 339 of file ItaniumDemangle.h . ◆  empty() bool NodeArray::empty ( ) const inline Definition at line 336 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseUnnamedTypeName() . ◆  end() Node ** NodeArray::end ( ) const inline Definition at line 340 of file ItaniumDemangle.h . ◆  operator[]() Node * NodeArray::operator[] ( size_t Idx ) const inline Definition at line 342 of file ItaniumDemangle.h . ◆  printAsString() bool NodeArray::printAsString ( OutputBuffer & OB ) const inline Definition at line 2658 of file ItaniumDemangle.h . References Fail , and Node::getKind() . ◆  printWithComma() void NodeArray::printWithComma ( OutputBuffer & OB ) const inline Definition at line 344 of file ItaniumDemangle.h . References Node::Comma . Referenced by llvm::ItaniumPartialDemangler::getFunctionParameters() . ◆  size() size_t NodeArray::size ( ) const inline Definition at line 337 of file ItaniumDemangle.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseExpr() . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/DemangleConfig_8h.html#a89bf5498ef5e9915f38a0da6adb156a3 | LLVM: include/llvm/Demangle/DemangleConfig.h File Reference LLVM  22.0.0git include llvm Demangle Macros DemangleConfig.h File Reference #include "llvm/Config/llvm-config.h" #include <cassert> Go to the source code of this file. Macros #define  __has_feature (x) #define  __has_cpp_attribute (x) #define  __has_attribute (x) #define  __has_builtin (x) #define  DEMANGLE_GNUC_PREREQ (maj, min, patch) #define  DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_UNREACHABLE #define  DEMANGLE_ATTRIBUTE_NOINLINE #define  DEMANGLE_DUMP_METHOD     DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED #define  DEMANGLE_FALLTHROUGH #define  DEMANGLE_ASSERT (__expr, __msg) #define  DEMANGLE_NAMESPACE_BEGIN    namespace llvm { namespace itanium_demangle { #define  DEMANGLE_NAMESPACE_END    } } #define  DEMANGLE_ABI   DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Macro Definition Documentation ◆  __has_attribute #define __has_attribute ( x ) Value: 0 Definition at line 30 of file DemangleConfig.h . ◆  __has_builtin #define __has_builtin ( x ) Value: 0 Definition at line 34 of file DemangleConfig.h . ◆  __has_cpp_attribute #define __has_cpp_attribute ( x ) Value: 0 Definition at line 26 of file DemangleConfig.h . ◆  __has_feature #define __has_feature ( x ) Value: 0 Definition at line 22 of file DemangleConfig.h . ◆  DEMANGLE_ABI #define DEMANGLE_ABI DEMANGLE_ABI is the export/visibility macro used to mark symbols delcared in llvm/Demangle as exported when built as a shared library. Definition at line 115 of file DemangleConfig.h . Referenced by llvm::ms_demangle::Node::output() , parse_discriminator() , and llvm::ms_demangle::Demangler::~Demangler() . ◆  DEMANGLE_ASSERT #define DEMANGLE_ASSERT ( __expr , __msg  ) Value: assert ((__expr) && (__msg)) assert assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!") Definition at line 94 of file DemangleConfig.h . Referenced by OutputBuffer::back() , PODSmallVector< Node *, 8 >::back() , ExplicitObjectParameter::ExplicitObjectParameter() , SpecialSubstitution::getBaseName() , AbstractManglingParser< Derived, Alloc >::OperatorInfo::getSymbol() , OutputBuffer::insert() , PODSmallVector< Node *, 8 >::operator[]() , AbstractManglingParser< Derived, Alloc >::parseTemplateParam() , AbstractManglingParser< Derived, Alloc >::parseUnresolvedName() , PODSmallVector< Node *, 8 >::pop_back() , AbstractManglingParser< Derived, Alloc >::popTrailingNodeArray() , PODSmallVector< Node *, 8 >::shrinkToSize() , Node::visit() , and AbstractManglingParser< Derived, Alloc >::ScopedTemplateParamList::~ScopedTemplateParamList() . ◆  DEMANGLE_ATTRIBUTE_NOINLINE #define DEMANGLE_ATTRIBUTE_NOINLINE Definition at line 69 of file DemangleConfig.h . ◆  DEMANGLE_ATTRIBUTE_USED #define DEMANGLE_ATTRIBUTE_USED Definition at line 53 of file DemangleConfig.h . ◆  DEMANGLE_DUMP_METHOD #define DEMANGLE_DUMP_METHOD    DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED Definition at line 73 of file DemangleConfig.h . Referenced by Node::dump() . ◆  DEMANGLE_FALLTHROUGH #define DEMANGLE_FALLTHROUGH Definition at line 85 of file DemangleConfig.h . Referenced by AbstractManglingParser< Derived, Alloc >::parseType() . ◆  DEMANGLE_GNUC_PREREQ #define DEMANGLE_GNUC_PREREQ ( maj , min , patch  ) Value: 0 Definition at line 46 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_BEGIN #define DEMANGLE_NAMESPACE_BEGIN   namespace llvm { namespace itanium_demangle { Definition at line 97 of file DemangleConfig.h . ◆  DEMANGLE_NAMESPACE_END #define DEMANGLE_NAMESPACE_END   } } Definition at line 98 of file DemangleConfig.h . ◆  DEMANGLE_UNREACHABLE #define DEMANGLE_UNREACHABLE Definition at line 61 of file DemangleConfig.h . Referenced by demanglePointerCVQualifiers() , ExpandedSpecialSubstitution::getBaseName() , and AbstractManglingParser< Derived, Alloc >::parseExpr() . Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fposativ%2Facrylamid#start-of-content | Sign in to GitHub · GitHub Skip to content You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert Sign in to GitHub {{ message }} --> Username or email address Password Forgot password? Uh oh! There was an error while loading. Please reload this page . New to GitHub? Create an account Sign in with a passkey Terms Privacy Docs Contact GitHub Support Manage cookies Do not share my personal information You can’t perform that action at this time. | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classPostfixQualifiedType.html#pub-methods | LLVM: PostfixQualifiedType Class Reference LLVM  22.0.0git Public Member Functions | List of all members PostfixQualifiedType Class Reference final #include " llvm/Demangle/ItaniumDemangle.h " Inheritance diagram for PostfixQualifiedType: This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead. [ legend ] Public Member Functions   PostfixQualifiedType ( const Node *Ty_, std::string_view Postfix_) template<typename Fn> void  match (Fn F ) const void  printLeft ( OutputBuffer &OB) const override Public Member Functions inherited from Node   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Additional Inherited Members Public Types inherited from Node enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Protected Attributes inherited from Node Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Detailed Description Definition at line 495 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  PostfixQualifiedType() PostfixQualifiedType::PostfixQualifiedType ( const Node * Ty_ , std::string_view Postfix_  ) inline Definition at line 500 of file ItaniumDemangle.h . References Node::Node() . Member Function Documentation ◆  match() template<typename Fn> void PostfixQualifiedType::match ( Fn F ) const inline Definition at line 503 of file ItaniumDemangle.h . References F . ◆  printLeft() void PostfixQualifiedType::printLeft ( OutputBuffer & OB ) const inline override virtual Implements Node . Definition at line 505 of file ItaniumDemangle.h . References Node::OutputBuffer . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/structNodeArrayNode.html#pub-attribs | LLVM: NodeArrayNode Struct Reference LLVM  22.0.0git Public Member Functions | Public Attributes | List of all members NodeArrayNode Struct Reference #include " llvm/Demangle/ItaniumDemangle.h " Inheritance diagram for NodeArrayNode: This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead. [ legend ] Public Member Functions   NodeArrayNode ( NodeArray Array_) template<typename Fn> void  match (Fn F ) const void  printLeft ( OutputBuffer &OB) const override Public Member Functions inherited from Node   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Public Attributes NodeArray   Array Additional Inherited Members Public Types inherited from Node enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Protected Attributes inherited from Node Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Detailed Description Definition at line 369 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  NodeArrayNode() NodeArrayNode::NodeArrayNode ( NodeArray Array_ ) inline Definition at line 371 of file ItaniumDemangle.h . References Array , and Node::Node() . Member Function Documentation ◆  match() template<typename Fn> void NodeArrayNode::match ( Fn F ) const inline Definition at line 373 of file ItaniumDemangle.h . References Array , and F . ◆  printLeft() void NodeArrayNode::printLeft ( OutputBuffer & OB ) const inline override virtual Implements Node . Definition at line 375 of file ItaniumDemangle.h . References Array , and Node::OutputBuffer . Member Data Documentation ◆  Array NodeArray NodeArrayNode::Array Definition at line 370 of file ItaniumDemangle.h . Referenced by match() , NodeArrayNode() , and printLeft() . The documentation for this struct was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/classObjCProtoName.html#pub-methods | LLVM: ObjCProtoName Class Reference LLVM  22.0.0git Public Member Functions | List of all members ObjCProtoName Class Reference #include " llvm/Demangle/ItaniumDemangle.h " Inheritance diagram for ObjCProtoName: This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead. [ legend ] Public Member Functions   ObjCProtoName ( const Node *Ty_, std::string_view Protocol_) template<typename Fn> void  match (Fn F ) const bool   isObjCObject () const std::string_view  getProtocol () const void  printLeft ( OutputBuffer &OB) const override Public Member Functions inherited from Node   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual std::string_view  getBaseName () const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Additional Inherited Members Public Types inherited from Node enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Protected Attributes inherited from Node Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Detailed Description Definition at line 614 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  ObjCProtoName() ObjCProtoName::ObjCProtoName ( const Node * Ty_ , std::string_view Protocol_  ) inline Definition at line 619 of file ItaniumDemangle.h . References Node::Node() . Member Function Documentation ◆  getProtocol() std::string_view ObjCProtoName::getProtocol ( ) const inline Definition at line 629 of file ItaniumDemangle.h . ◆  isObjCObject() bool ObjCProtoName::isObjCObject ( ) const inline Definition at line 624 of file ItaniumDemangle.h . References getName() . Referenced by PointerType::printLeft() , and PointerType::printRight() . ◆  match() template<typename Fn> void ObjCProtoName::match ( Fn F ) const inline Definition at line 622 of file ItaniumDemangle.h . References F . ◆  printLeft() void ObjCProtoName::printLeft ( OutputBuffer & OB ) const inline override virtual Implements Node . Definition at line 631 of file ItaniumDemangle.h . References Node::OutputBuffer . The documentation for this class was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/structNestedName.html#aa209a0cde0a987d445563144d63a7a72 | LLVM: NestedName Struct Reference LLVM  22.0.0git Public Member Functions | Public Attributes | List of all members NestedName Struct Reference #include " llvm/Demangle/ItaniumDemangle.h " Inheritance diagram for NestedName: This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead. [ legend ] Public Member Functions   NestedName ( Node *Qual_, Node *Name_) template<typename Fn> void  match (Fn F ) const std::string_view  getBaseName () const override void  printLeft ( OutputBuffer &OB) const override Public Member Functions inherited from Node   Node ( Kind K_, Prec Precedence_= Prec::Primary , Cache RHSComponentCache_= Cache::No , Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No )   Node ( Kind K_, Cache RHSComponentCache_, Cache ArrayCache_= Cache::No , Cache FunctionCache_= Cache::No ) template<typename Fn> void  visit (Fn F ) const   Visit the most-derived object corresponding to this object. bool   hasRHSComponent ( OutputBuffer &OB) const bool   hasArray ( OutputBuffer &OB) const bool   hasFunction ( OutputBuffer &OB) const Kind   getKind () const Prec   getPrecedence () const Cache   getRHSComponentCache () const Cache   getArrayCache () const Cache   getFunctionCache () const virtual bool   hasRHSComponentSlow ( OutputBuffer &) const virtual bool   hasArraySlow ( OutputBuffer &) const virtual bool   hasFunctionSlow ( OutputBuffer &) const virtual const Node *  getSyntaxNode ( OutputBuffer &) const void  printAsOperand ( OutputBuffer &OB, Prec P = Prec::Default , bool StrictlyWorse=false) const void  print ( OutputBuffer &OB) const virtual bool   printInitListAsType ( OutputBuffer &, const NodeArray &) const virtual  ~Node ()=default DEMANGLE_DUMP_METHOD void  dump () const Public Attributes Node *  Qual Node *  Name Additional Inherited Members Public Types inherited from Node enum   Kind : uint8_t enum class   Cache : uint8_t { Yes , No , Unknown }   Three-way bool to track a cached value. More... enum class   Prec : uint8_t {    Primary , Postfix , Unary , Cast ,    PtrMem , Multiplicative , Additive , Shift ,    Spaceship , Relational , Equality , And ,    Xor , Ior , AndIf , OrIf ,    Conditional , Assign , Comma , Default }   Operator precedence for expression nodes. More... Protected Attributes inherited from Node Cache   RHSComponentCache : 2   Tracks if this node has a component on its right side, in which case we need to call printRight. Cache   ArrayCache : 2   Track if this node is a (possibly qualified) array type. Cache   FunctionCache : 2   Track if this node is a (possibly qualified) function type. Detailed Description Definition at line 1077 of file ItaniumDemangle.h . Constructor & Destructor Documentation ◆  NestedName() NestedName::NestedName ( Node * Qual_ , Node * Name_  ) inline Definition at line 1081 of file ItaniumDemangle.h . References Name , Node::Node() , and Qual . Member Function Documentation ◆  getBaseName() std::string_view NestedName::getBaseName ( ) const inline override virtual Reimplemented from Node . Definition at line 1086 of file ItaniumDemangle.h . References Name . ◆  match() template<typename Fn> void NestedName::match ( Fn F ) const inline Definition at line 1084 of file ItaniumDemangle.h . References F , Name , and Qual . ◆  printLeft() void NestedName::printLeft ( OutputBuffer & OB ) const inline override virtual Implements Node . Definition at line 1088 of file ItaniumDemangle.h . References Name , Node::OutputBuffer , and Qual . Member Data Documentation ◆  Name Node * NestedName::Name Definition at line 1079 of file ItaniumDemangle.h . Referenced by getBaseName() , match() , NestedName() , and printLeft() . ◆  Qual Node * NestedName::Qual Definition at line 1078 of file ItaniumDemangle.h . Referenced by match() , NestedName() , and printLeft() . The documentation for this struct was generated from the following file: include/llvm/Demangle/ ItaniumDemangle.h Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://llvm.org/doxygen/ComplexDeinterleavingPass_8cpp.html#a2762113571c7956c9818c452b2d256ae | LLVM: lib/CodeGen/ComplexDeinterleavingPass.cpp File Reference LLVM  22.0.0git lib CodeGen Classes | Macros | Typedefs | Functions | Variables ComplexDeinterleavingPass.cpp File Reference #include " llvm/CodeGen/ComplexDeinterleavingPass.h " #include " llvm/ADT/AllocatorList.h " #include " llvm/ADT/MapVector.h " #include " llvm/ADT/Statistic.h " #include " llvm/Analysis/TargetLibraryInfo.h " #include " llvm/Analysis/TargetTransformInfo.h " #include " llvm/CodeGen/TargetLowering.h " #include " llvm/CodeGen/TargetSubtargetInfo.h " #include " llvm/IR/IRBuilder.h " #include " llvm/IR/Intrinsics.h " #include " llvm/IR/PatternMatch.h " #include " llvm/InitializePasses.h " #include " llvm/Support/Allocator.h " #include " llvm/Target/TargetMachine.h " #include " llvm/Transforms/Utils/Local.h " #include <algorithm> Go to the source code of this file. Classes struct   llvm::DenseMapInfo< ComplexValue > Macros #define  DEBUG_TYPE    "complex-deinterleaving" Typedefs typedef SmallVector < struct ComplexValue, 2 >  ComplexValues Functions   STATISTIC (NumComplexTransformations, "Amount of complex patterns transformed") static bool   isInterleavingMask ( ArrayRef < int > Mask)   Checks the given mask, and determines whether said mask is interleaving. static bool   isDeinterleavingMask ( ArrayRef < int > Mask)   Checks the given mask, and determines whether said mask is deinterleaving. static bool   isNeg ( Value *V)   Returns true if the operation is a negation of V, and it works for both integers and floats. static Value *  getNegOperand ( Value *V)   Returns the operand for negation operation.   INITIALIZE_PASS_BEGIN (ComplexDeinterleavingLegacyPass, DEBUG_TYPE , "Complex Deinterleaving", false, false) INITIALIZE_PASS_END (ComplexDeinterleavingLegacyPass static bool   isInstructionPairAdd ( Instruction * A , Instruction * B ) static bool   isInstructionPairMul ( Instruction * A , Instruction * B ) static bool   isInstructionPotentiallySymmetric ( Instruction * I ) static Value *  replaceSymmetricNode ( IRBuilderBase & B , unsigned Opcode, std::optional< FastMathFlags > Flags, Value *InputA, Value *InputB) Variables static cl::opt < bool >  ComplexDeinterleavingEnabled ("enable-complex-deinterleaving", cl::desc ("Enable generation of complex instructions"), cl::init(true), cl::Hidden)   DEBUG_TYPE Complex  Deinterleaving Complex  false Macro Definition Documentation ◆  DEBUG_TYPE #define DEBUG_TYPE   "complex-deinterleaving" Definition at line 82 of file ComplexDeinterleavingPass.cpp . Typedef Documentation ◆  ComplexValues typedef SmallVector <struct ComplexValue, 2> ComplexValues Definition at line 127 of file ComplexDeinterleavingPass.cpp . Function Documentation ◆  getNegOperand() Value * getNegOperand ( Value * V ) static Returns the operand for negation operation. Definition at line 616 of file ComplexDeinterleavingPass.cpp . References assert() , llvm::cast() , I , and isNeg() . ◆  INITIALIZE_PASS_BEGIN() INITIALIZE_PASS_BEGIN ( ComplexDeinterleavingLegacyPass , DEBUG_TYPE , "Complex Deinterleaving" , false , false  ) References DEBUG_TYPE . ◆  isDeinterleavingMask() bool isDeinterleavingMask ( ArrayRef < int > Mask ) static Checks the given mask, and determines whether said mask is deinterleaving. To be deinterleaving, a mask must increment in steps of 2, and either start with 0 or 1. (e.g. an 8x vector deinterleaving mask would be either <0, 2, 4, 6> or <1, 3, 5, 7>). Definition at line 600 of file ComplexDeinterleavingPass.cpp . References llvm::Offset . ◆  isInstructionPairAdd() bool isInstructionPairAdd ( Instruction * A , Instruction * B  ) static Definition at line 916 of file ComplexDeinterleavingPass.cpp . References A() , and B() . ◆  isInstructionPairMul() bool isInstructionPairMul ( Instruction * A , Instruction * B  ) static Definition at line 926 of file ComplexDeinterleavingPass.cpp . References A() , B() , llvm::PatternMatch::m_BinOp() , llvm::PatternMatch::m_FMul() , llvm::PatternMatch::m_Value() , and llvm::PatternMatch::match() . ◆  isInstructionPotentiallySymmetric() bool isInstructionPotentiallySymmetric ( Instruction * I ) static Definition at line 933 of file ComplexDeinterleavingPass.cpp . References I . ◆  isInterleavingMask() bool isInterleavingMask ( ArrayRef < int > Mask ) static Checks the given mask, and determines whether said mask is interleaving. To be interleaving, a mask must alternate between i and i + (Length / / 2) , and must contain all numbers within the range of [0..Length) (e.g. a 4x vector interleaving mask would be <0, 2, 1, 3>). Definition at line 585 of file ComplexDeinterleavingPass.cpp . ◆  isNeg() bool isNeg ( Value * V ) static Returns true if the operation is a negation of V, and it works for both integers and floats. Definition at line 612 of file ComplexDeinterleavingPass.cpp . References llvm::PatternMatch::m_FNeg() , llvm::MIPatternMatch::m_Neg() , llvm::PatternMatch::m_Value() , and llvm::PatternMatch::match() . Referenced by DecodeBFLabelOperand() , expandMOVImmSimple() , getNegOperand() , KnuthDiv() , llvm::APIntOps::RoundDoubleToAPInt() , llvm::APInt::roundToDouble() , and llvm::utostr() . ◆  replaceSymmetricNode() Value * replaceSymmetricNode ( IRBuilderBase & B , unsigned Opcode , std::optional< FastMathFlags > Flags , Value * InputA , Value * InputB  ) static Definition at line 2281 of file ComplexDeinterleavingPass.cpp . References B() , llvm::cast() , I , and llvm_unreachable . ◆  STATISTIC() STATISTIC ( NumComplexTransformations , "Amount of complex patterns transformed"  ) Variable Documentation ◆  ComplexDeinterleavingEnabled cl::opt < bool > ComplexDeinterleavingEnabled("enable-complex-deinterleaving", cl::desc ("Enable generation of complex instructions"), cl::init(true), cl::Hidden) ( "enable-complex-deinterleaving" , cl::desc ("Enable generation of complex instructions") , cl::init(true) , cl::Hidden  ) static ◆  DEBUG_TYPE DEBUG_TYPE Definition at line 531 of file ComplexDeinterleavingPass.cpp . ◆  Deinterleaving Complex Deinterleaving Definition at line 532 of file ComplexDeinterleavingPass.cpp . ◆  false Complex false Definition at line 532 of file ComplexDeinterleavingPass.cpp . Generated on for LLVM by  1.14.0 | 2026-01-13T09:30:39 |
https://github.com/docker/build-push-action | GitHub - docker/build-push-action: GitHub Action to build and push Docker images with Buildx Skip to content Navigation Menu Toggle navigation Sign in Appearance settings Platform AI CODE CREATION GitHub Copilot Write better code with AI GitHub Spark Build and deploy intelligent apps GitHub Models Manage and compare prompts MCP Registry New Integrate external tools DEVELOPER WORKFLOWS Actions Automate any workflow Codespaces Instant dev environments Issues Plan and track work Code Review Manage code changes APPLICATION SECURITY GitHub Advanced Security Find and fix vulnerabilities Code security Secure your code as you build Secret protection Stop leaks before they start EXPLORE Why GitHub Documentation Blog Changelog Marketplace View all features Solutions BY COMPANY SIZE Enterprises Small and medium teams Startups Nonprofits BY USE CASE App Modernization DevSecOps DevOps CI/CD View all use cases BY INDUSTRY Healthcare Financial services Manufacturing Government View all industries View all solutions Resources EXPLORE BY TOPIC AI Software Development DevOps Security View all topics EXPLORE BY TYPE Customer stories Events & webinars Ebooks & reports Business insights GitHub Skills SUPPORT & SERVICES Documentation Customer support Community forum Trust center Partners Open Source COMMUNITY GitHub Sponsors Fund open source developers PROGRAMS Security Lab Maintainer Community Accelerator Archive Program REPOSITORIES Topics Trending Collections Enterprise ENTERPRISE SOLUTIONS Enterprise platform AI-powered developer platform AVAILABLE ADD-ONS GitHub Advanced Security Enterprise-grade security features Copilot for Business Enterprise-grade AI features Premium Support Enterprise-grade 24/7 support Pricing Search or jump to... Search code, repositories, users, issues, pull requests... --> Search Clear Search syntax tips Provide feedback --> We read every piece of feedback, and take your input very seriously. Include my email address so I can be contacted Cancel Submit feedback Saved searches Use saved searches to filter your results more quickly --> Name Query To see all available qualifiers, see our documentation . Cancel Create saved search Sign in Sign up Appearance settings Resetting focus You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert {{ message }} docker / build-push-action Public Notifications You must be signed in to change notification settings Fork 697 Star 5.1k GitHub Action to build and push Docker images with Buildx github.com/marketplace/actions/build-and-push-docker-images License Apache-2.0 license 5.1k stars 697 forks Branches Tags Activity Star Notifications You must be signed in to change notification settings Code Issues 41 Pull requests 12 Discussions Actions Projects 0 Security Uh oh! There was an error while loading. Please reload this page . Insights Additional navigation options Code Issues Pull requests Discussions Actions Projects Security Insights docker/build-push-action Use this GitHub action with your project Add this Action to an existing workflow or create a new one View on Marketplace master Branches Tags Go to file Code Open more actions menu Folders and files Name Name Last commit message Last commit date Latest commit History 1,065 Commits .github .github .yarn/ plugins/ @yarnpkg .yarn/ plugins/ @yarnpkg __mocks__/ @actions __mocks__/ @actions __tests__ __tests__ dist dist src src test test .dockerignore .dockerignore .editorconfig .editorconfig .gitattributes .gitattributes .gitignore .gitignore .prettierignore .prettierignore .prettierrc.json .prettierrc.json .yarnrc.yml .yarnrc.yml LICENSE LICENSE README.md README.md TROUBLESHOOTING.md TROUBLESHOOTING.md action.yml action.yml codecov.yml codecov.yml dev.Dockerfile dev.Dockerfile docker-bake.hcl docker-bake.hcl eslint.config.js eslint.config.js jest.config.js jest.config.js package.json package.json tsconfig.json tsconfig.json yarn.lock yarn.lock View all files Repository files navigation README Code of conduct Contributing Apache-2.0 license Security About GitHub Action to build and push Docker images with Buildx with full support of the features provided by Moby BuildKit builder toolkit. This includes multi-platform build, secrets, remote cache, etc. and different builder deployment/namespacing options. Usage Git context Path context Examples Summaries Customizing inputs outputs environment variables Troubleshooting Contributing Usage In the examples below we are also using 3 other actions: setup-buildx action will create and boot a builder using by default the docker-container driver . This is not required but recommended using it to be able to build multi-platform images, export cache, etc. setup-qemu action can be useful if you want to add emulation support with QEMU to be able to build against more platforms. login action will take care to log in against a Docker registry. Git context By default, this action uses the Git context , so you don't need to use the actions/checkout action to check out the repository as this will be done directly by BuildKit . The git reference will be based on the event that triggered your workflow and will result in the following context: https://github.com/<owner>/<repo>.git#<ref> . name : ci on : push : jobs : docker : runs-on : ubuntu-latest steps : - name : Login to Docker Hub uses : docker/login-action@v3 with : username : ${{ vars.DOCKERHUB_USERNAME }} password : ${{ secrets.DOCKERHUB_TOKEN }} - name : Set up QEMU uses : docker/setup-qemu-action@v3 - name : Set up Docker Buildx uses : docker/setup-buildx-action@v3 - name : Build and push uses : docker/build-push-action@v6 with : push : true tags : user/app:latest Be careful because any file mutation in the steps that precede the build step will be ignored, including processing of the .dockerignore file since the context is based on the Git reference. However, you can use the Path context using the context input alongside the actions/checkout action to remove this restriction. Default Git context can also be provided using the Handlebars template expression {{defaultContext}} . Here we can use it to provide a subdirectory to the default Git context: - name : Build and push uses : docker/build-push-action@v6 with : context : " {{defaultContext}}:mysubdir " push : true tags : user/app:latest Building from the current repository automatically uses the GitHub Token , so it does not need to be passed. If you want to authenticate against another private repository, you have to use a secret named GIT_AUTH_TOKEN to be able to authenticate against it with Buildx: - name : Build and push uses : docker/build-push-action@v6 with : push : true tags : user/app:latest secrets : | GIT_AUTH_TOKEN=${{ secrets.MYTOKEN }} Path context name : ci on : push : jobs : docker : runs-on : ubuntu-latest steps : - name : Checkout uses : actions/checkout@v5 - name : Login to Docker Hub uses : docker/login-action@v3 with : username : ${{ vars.DOCKERHUB_USERNAME }} password : ${{ secrets.DOCKERHUB_TOKEN }} - name : Set up QEMU uses : docker/setup-qemu-action@v3 - name : Set up Docker Buildx uses : docker/setup-buildx-action@v3 - name : Build and push uses : docker/build-push-action@v6 with : context : . push : true tags : user/app:latest Examples Multi-platform image Secrets Push to multi-registries Manage tags and labels Cache management Export to Docker Test before push Validating build configuration Local registry Share built image between jobs Named contexts Copy image between registries Update Docker Hub repo description SBOM and provenance attestations Annotations Reproducible builds Summaries This action generates a job summary that provides a detailed overview of the build execution. The summary shows an overview of all the steps executed during the build, including the build inputs and eventual errors. The summary also includes a link for downloading the build record with additional details about the build, including build stats, logs, outputs, and more. The build record can be imported to Docker Desktop for inspecting the build in greater detail. Warning If you're using the actions/download-artifact action in your workflow, you need to ignore the build record artifacts if name and pattern inputs are not specified ( defaults to download all artifacts of the workflow), otherwise the action will fail: - uses : actions/download-artifact@v4 with : pattern : " !*.dockerbuild " More info: actions/toolkit#1874 Summaries are enabled by default, but can be disabled with the DOCKER_BUILD_SUMMARY environment variable . For more information about summaries, refer to the documentation . Customizing inputs The following inputs can be used as step.with keys: List type is a newline-delimited string cache-from : | user/app:cache type=local,src=path/to/dir CSV type is a comma-delimited string tags : name/app:latest,name/app:1.0.0 Name Type Description add-hosts List/CSV List of customs host-to-IP mapping (e.g., docker:10.180.0.1 ) allow List/CSV List of extra privileged entitlement (e.g., network.host,security.insecure ) annotations List List of annotation to set to the image attests List List of attestation parameters (e.g., type=sbom,generator=image ) builder String Builder instance (see setup-buildx action) build-args List List of build-time variables build-contexts List List of additional build contexts (e.g., name=path ) cache-from List List of external cache sources (e.g., type=local,src=path/to/dir ) cache-to List List of cache export destinations (e.g., type=local,dest=path/to/dir ) call String Set method for evaluating build (e.g., check ) cgroup-parent String Optional parent cgroup for the container used in the build context String Build's context is the set of files located in the specified PATH or URL (default Git context ) file String Path to the Dockerfile. (default {context}/Dockerfile ) labels List List of metadata for an image load Bool Load is a shorthand for --output=type=docker (default false ) network String Set the networking mode for the RUN instructions during build no-cache Bool Do not use cache when building the image (default false ) no-cache-filters List/CSV Do not cache specified stages outputs List List of output destinations (format: type=local,dest=path ) platforms List/CSV List of target platforms for build provenance Bool/String Generate provenance attestation for the build (shorthand for --attest=type=provenance ) pull Bool Always attempt to pull all referenced images (default false ) push Bool Push is a shorthand for --output=type=registry (default false ) sbom Bool/String Generate SBOM attestation for the build (shorthand for --attest=type=sbom ) secrets List List of secrets to expose to the build (e.g., key=string , GIT_AUTH_TOKEN=mytoken ) secret-envs List/CSV List of secret env vars to expose to the build (e.g., key=envname , MY_SECRET=MY_ENV_VAR ) secret-files List List of secret files to expose to the build (e.g., key=filename , MY_SECRET=./secret.txt ) shm-size String Size of /dev/shm (e.g., 2g ) ssh List List of SSH agent socket or keys to expose to the build tags List/CSV List of tags target String Sets the target stage to build ulimit List Ulimit options (e.g., nofile=1024:1024 ) github-token String GitHub Token used to authenticate against a repository for Git context (default ${{ github.token }} ) outputs The following outputs are available: Name Type Description imageid String Image ID digest String Image digest metadata JSON Build result metadata environment variables Name Type Default Description DOCKER_BUILD_CHECKS_ANNOTATIONS Bool true If false , GitHub annotations are not generated for build checks DOCKER_BUILD_SUMMARY Bool true If false , build summary generation is disabled DOCKER_BUILD_RECORD_UPLOAD Bool true If false , build record upload as GitHub artifact is disabled DOCKER_BUILD_RECORD_RETENTION_DAYS Number Duration after which build record artifact will expire in days. Defaults to repository/org retention settings if unset or 0 DOCKER_BUILD_EXPORT_LEGACY Bool false If true , exports build using legacy export-build tool instead of buildx history export command Troubleshooting See TROUBLESHOOTING.md Contributing Want to contribute? Awesome! You can find information about contributing to this project in the CONTRIBUTING.md About GitHub Action to build and push Docker images with Buildx github.com/marketplace/actions/build-and-push-docker-images Topics docker dockerhub github-actions buildx github-actions-docker Resources Readme License Apache-2.0 license Code of conduct Code of conduct Contributing Contributing Security policy Security policy Uh oh! There was an error while loading. Please reload this page . Activity Custom properties Stars 5.1k stars Watchers 37 watching Forks 697 forks Report repository Releases 58 v6.18.0 Latest May 27, 2025 + 57 releases Packages 0 Uh oh! There was an error while loading. Please reload this page . Used by 771k + 771,171 Contributors 44 + 30 contributors Languages TypeScript 87.1% Dockerfile 7.1% JavaScript 3.8% HCL 1.7% Go 0.3% Footer © 2026 GitHub, Inc. Footer navigation Terms Privacy Security Status Community Docs Contact Manage cookies Do not share my personal information You can’t perform that action at this time. | 2026-01-13T09:30:39 |
https://www.php.net/x-myracloud-5958a2bbbed300a9b9ac631223924e0b/1768296252.434 | PHP update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box A popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world. What's new in 8.5 Download 8.5.1 · Changelog · Upgrading 8.4.16 · Changelog · Upgrading 8.3.29 · Changelog · Upgrading 8.2.30 · Changelog · Upgrading 18 Dec 2025 PHP 8.1.34 Released! The PHP development team announces the immediate availability of PHP 8.1.34. This is a security release. All PHP 8.1 users are encouraged to upgrade to this version. For source downloads of PHP 8.1.34 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.4.16 Released! The PHP development team announces the immediate availability of PHP 8.4.16. This is a security release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.16 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.2.30 Released! The PHP development team announces the immediate availability of PHP 8.2.30. This is a security release. All PHP 8.2 users are encouraged to upgrade to this version. For source downloads of PHP 8.2.30 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.3.29 Released! The PHP development team announces the immediate availability of PHP 8.3.29. This is a security release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.29 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.5.1 Released! The PHP development team announces the immediate availability of PHP 8.5.1. This is a security release. All PHP 8.5 users are encouraged to upgrade to this version. For source downloads of PHP 8.5.1 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.5.0 Released! The PHP development team announces the immediate availability of PHP 8.5.0. This release marks the latest minor release of the PHP language. PHP 8.5 comes with numerous improvements and new features such as: New "URI" extension New pipe operator (|>) Clone With New #[\NoDiscard] attribute Support for closures, casts, and first class callables in constant expressions And much much more... For source downloads of PHP 8.5.0 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . The migration guide is available in the PHP Manual. Please consult it for the detailed list of new features and backward incompatible changes. Kudos to all the contributors and supporters! 20 Nov 2025 PHP 8.4.15 Released! The PHP development team announces the immediate availability of PHP 8.4.15. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.15 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.3.28 Released! The PHP development team announces the immediate availability of PHP 8.3.28. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.28 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 13 Nov 2025 PHP 8.5.0 RC 5 available for testing The PHP team is pleased to announce the fifth release candidate of PHP 8.5.0, RC 5. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC5, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 06 Nov 2025 PHP 8.5.0 RC4 available for testing The PHP team is pleased to announce the final planned release candidate of PHP 8.5.0, RC 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC4, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 23 Oct 2025 PHP 8.3.27 Released! The PHP development team announces the immediate availability of PHP 8.3.27. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.27 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.4.14 Released! The PHP development team announces the immediate availability of PHP 8.4.14. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.14 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.5.0 RC 3 available for testing The PHP team is pleased to announce the third release candidate of PHP 8.5.0, RC 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC4, planned for 6 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 09 Oct 2025 PHP 8.5.0 RC 2 available for testing The PHP team is pleased to announce the second release candidate of PHP 8.5.0, RC 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC2, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC3, planned for 23 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.5.0 RC 1 available for testing The PHP team is pleased to announce the first release candidate of PHP 8.5.0, RC 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC1, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC2, planned for 9 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.3.26 Released! The PHP development team announces the immediate availability of PHP 8.3.26. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.26 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 25 Sep 2025 PHP 8.4.13 Released! The PHP development team announces the immediate availability of PHP 8.4.13. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.13 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 11 Sep 2025 PHP 8.5.0 Beta 3 available for testing The PHP team is pleased to announce the third beta release of PHP 8.5.0, Beta 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC1, planned for 25 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.5.0 Beta 2 available for testing The PHP team is pleased to announce the second beta release of PHP 8.5.0, Beta 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 2 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 3, planned for 11 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.3.25 Released! The PHP development team announces the immediate availability of PHP 8.3.25. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.25 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 28 Aug 2025 PHP 8.4.12 Released! The PHP development team announces the immediate availability of PHP 8.4.12. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.12 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 14 Aug 2025 PHP 8.5.0 Beta 1 available for testing The PHP team is pleased to announce the first beta release of PHP 8.5.0, Beta 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 1 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 2, planned for 28 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 01 Aug 2025 PHP 8.5.0 Alpha 4 available for testing The PHP team is pleased to announce the third testing release of PHP 8.5.0, Alpha 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Alpha 4 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 1, planned for 14 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 31 Jul 2025 PHP 8.4.11 Released! The PHP development team announces the immediate availability of PHP 8.4.11. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.11 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 31 Jul 2025 PHP 8.3.24 Released! The PHP development team announces the immediate availability of PHP 8.3.24. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.24 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . Older News Entries The PHP Foundation The PHP Foundation is a collective of people and organizations, united in the mission to ensure the long-term prosperity of the PHP language. Donate Upcoming conferences International PHP Conference Berlin 2026 Laravel Live Japan Conferences calling for papers Dutch PHP Conference 2026 User Group Events Special Thanks Social media @official_php @php@fosstodon.org @phpnet Copyright © 2001-2026 The PHP Group My PHP.net Contact Other PHP.net sites Privacy policy View Source ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:39 |
https://www.timeforkids.com/g56/#main-content | TIME for Kids | Articles | G5-6 Skip to main content Search Articles by Grade level Grades K-1 Articles Grade 2 Articles Grades 3-4 Articles Grades 5-6 Articles Topics Animals Arts Ask Angela Books Business Careers Community Culture Debate Earth Science Education Election 2024 Engineering Environment Food and Nutrition Games Government History Holidays Inventions Movies and Television Music and Theater Nature News People Places Podcasts Science Service Stars Space Sports The Human Body The View Transportation Weather World Young Game Changers Your $ Financial Literacy Content Grade 4 Edition Grade 5-6 Edition For Grown-ups Resource Spotlight Also from TIME for Kids: Log In role: none user_age: none editions: The page you are about to enter is for grown-ups. Enter your birth date to continue. Month (MM) 01 02 03 04 05 06 07 08 09 10 11 12 Year (YYYY) 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 Submit Articles K-1 2 3-4 5-6 Business Cities by Design January 12, 2026 No two cities are alike. While they may feature the same elements—buildings and houses, roads and highways, parks and shopping centers—every city is arranged differently. Geography, climate, and culture are just a few of the factors that influence how a… Community Mission: Spread Kindness January 9, 2026 Join a community of kids who are making the world a better and brighter place. TFK Service Stars know that even the smallest actions can make a big impact. Mission of the Month Kindness counts! We’ll feature kids who are… Audio United States After the Fires January 9, 2026 One year ago, the Palisades and Eaton Fires devastated Los Angeles, California. Since then, community members have been working to rebuild. The fires began on January 7, 2025, and were propelled by dry conditions and wind speeds as high… Audio Technology Warning Labels Required January 8, 2026 On December 26, New York confirmed a new law to protect kids’ mental health. It requires social-media platforms to warn users under age 18 about addictive features, such as autoplay, infinite scroll, and like counts. These features entice users to… Audio World Snow Beast January 8, 2026 An enormous snow tiger watches over the Harbin Ice and Snow World on January 5. Visitors to the yearly festival in Harbin, China, marvel at giant snow and ice s… Audio Technology Tech Show and Tell January 8, 2026 Tech fans attended the Consumer Electronics Show (CES) from January 6 to 9. The yearly showcase takes place in Las Vegas, Nevada. It allows tech companies to show off their newest products. This year, many companies presented robots. For example,… Audio Business What’s Your Spark? January 8, 2026 We love hearing about your dreams, your ideas, and the things that light you up. Whether you know exactly what you want your future career to be or are still figuring it out, your answers show just how creative and… Science Stealing Stings January 7, 2026 Thieves are lurking below the surface of the oceans. They don’t wear ski masks, with only their eyes visible. In fact, they don’t have real eyes at all. These thieves are colorful sea slugs called nudibranchs, and they’re found in… Audio Spanish Community Legacy Building January 7, 2026 When Legacy Jackson was 2, she and her family spent a cold Christmas morning in downtown St. Louis, Missouri. They were handing out hot soup and warm clothes to people in need. Legacy’s mom, Kynedra Ogunnaike, says volunteering is a… Audio Community Star Power: Patrick Finnegan January 2, 2026 Meet Service Star Patrick Finnegan,12, who volunteers as a peer mediator in Savannah, Georgia. TFK Kid Reporter Madeline Martinez spoke with Patrick about his efforts. What does a peer mediator do? They oversee a conflict that two or more students… Audio World TIME Person of the Year January 2, 2026 TIME’s 2025 Person of the Year isn’t a person. It’s a group: the architects of artificial intelligence. This group includes AI innovators such as OpenAI CEO Sam Altman, Nvidia’s Jensen Huang, and Lisa Su, the CEO of Advanced Micro Devices.… Audio World Commuting in the Clouds January 1, 2026 Paris, France, unveiled a three-mile cable car route on December 13. It’s the first cable car route in the region, and the longest urban route in Europe. Commuters in the suburbs of Paris can now float over rush-hour traffic. The… Audio World Ready to Celebrate January 1, 2026 This shop in Liaoning Province, China, is one of many getting ready for Lunar New Year celebrations. February 17 will kick off the Year of the Fire Horse, which… Audio Penniless! January 1, 2026 People pick them up for good luck. They’re tossed into fountains and valued by collectors. More than 3 billion pennies were made in 2024 alone. And on November 12, 2025, the United States Mint produced its final batch. After 232… Audio Spanish Science Ancient Ice December 31, 2025 Imagine the Earth a million years ago. Was it warmer or colder? Was the air different? To find out, an international group of scientists took a peek back in time—not with a time machine, but with ancient ice. Working on… Audio Health Ask Angela: Up at Night December 31, 2025 Have questions? Angela Haupt connects with experts and shares their words of wisdom. Angela Haupt is a health and wellness editor at TIME. She talks with experts about problems readers are having, then writes articles to share what she learns.… Audio Time Off New Classics December 31, 2025 From TV shows to fashion, hits from the 1980s and’90s are popular again. Game companies are getting in on the trend. Inspired by the old-school arcade experience, new and upcoming video games are packed with kooky colors and plenty of… Audio Community Star Power: Shubham Roy-Choudhury December 19, 2025 Meet Service Star Shubham Roy-Choudhury, 14. He’s the founder of Lunar Academy, a student-led program in New Jersey. It provides free tutoring and educational resources. TFK Kid Reporter Vicky Sun spoke with Shubham about his efforts. What motivated you to… Audio Posts pagination 1 2 3 4 5 … 50 Next Contact us Privacy policy California privacy Terms of Service Subscribe CLASSROOM INTERNATIONAL © 2026 TIME USA, LLC. All Rights Reserved. Powered by WordPress.com VIP | 2026-01-13T09:30:39 |
https://reinvent.awsevents.com/keynotes/?trk=www.google.com | AWS re:Invent 2025 Watch on demand | Amazon Web Services On demand Professional Focus Build and develop Strategy and leadership Sponsors Subscribe for updates Log in Watch on demand Relive highlights from AWS re:Invent 2025. From keynotes to Innovation Talks to breakout sessions and more, discover this year’s top announcements and exciting array of new products. Read the lastest Keynotes Innovation Talks Featured content Breakout sessions Opening Keynote with Matt Garman Inventing what’s next: AWS helps everyone build the new AI world Matt Garman CEO, AWS Learn how AWS gives customers the freedom and confidence to invent and scale with AI. By running the world’s largest AI infrastructure and innovating at every layer of the stack, AWS provides the security and performance customers need to build custom AI agents that deliver real value, now. Learn more about AI agents Opening Keynote with Matt Garman The customer stories behind the keynote John Kodera Chief Digital Officer and Corporate Executive Officer, Sony Group Corporation John Kodera explains how Sony continually aims to deliver emotionally resonant experiences by connecting fans with creators and leveraging state-of-the-art technology from AWS that harnesses data and AI. --> Watch customer keynote Shantanu Narayen Chair and Chief Executive Officer, Adobe Shantanu Narayen shares how Adobe works with AWS to transform digital experiences with innovative AI capabilities for business professionals and consumers, creators and creative professionals, and marketing professionals. --> Learn more Watch customer keynote May Habib Chief Executive Officer and Cofounder, WRITER Learn how WRITER is working with AWS to empower businesses and transform work at scale, with agentic workflows powered by WRITER’s Palmyra X5 model and integration with Amazon Bedrock for improved governance and security. --> Learn more Watch customer keynote The Future of Agentic AI is Here Swami Sivasubramanian VP, Agentic AI, AWS AWS makes it easier for anyone to build and use agents to completely reinvent how to translate problems into solutions. This isn't just about doing routine things faster. It's about making us all more effective and empowered by unlocking capabilities that, before, we couldn't even imagine. Learn more about AI agents The Future of Agentic AI Is Here The customer stories behind the keynote Guillermo Rauch CEO and Founder, Vercel Vercel provides developers with a platform for quickly creating and scaling websites and applications. In building its AI coding agent, v0, Vercel used Amazon Bedrock to help it meet demand spikes and stay at the forefront of what’s possible, even as the company constantly iterated. --> Watch customer keynote William Brennan Vice President of Technology Transformation, Blue Origin Blue Origin is building the future of space exploration, including residences on the moon, using agentic AI on AWS. Last month, over 70% of its employees interacted with 2,100 agents in production, helping accelerate the product lifecycle, increase production, and reduce the cost of access to space. --> Learn more Watch customer keynote The Partnership Advantage Dr. Ruba Borno VP, Global Specialists and Partners, AWS AWS helps customers discover the magic of AI agents by providing the most secure cloud, the broadest toolkit, and the best community of partners, the AWS Partner Network. Customers working with AWS certified partners move faster and with more success in moving AI projects into production. Learn about Partner AI agents The Partnership Advantage The customer stories behind the keynote Sanjay Bhakta Chief Product and Technology Officer, Condé Nast Condé Nast consolidated its data platforms onto Databricks running on AWS to streamline infrastructure and power AI solutions for content rights management, content moderation, and more. This move saved the company $6 million annually, increased revenue, and enhanced the customer experience. --> Learn more Watch customer keynote Infrastructure Innovations Peter DeSantis SVP, Utility Computing, AWS Dave Brown VP, Compute and Machine Learning Services, AWS AWS’s focus on security, elasticity, availability, cost, and agility has become even more important in the AI-driven world. From the AWS Nitro System to new generations of AWS AI chips, AWS continues to invest in infrastructure innovation so that customers can build without making tradeoffs. Learn about AWS chips Infrastructure Innovations The customer stories behind the keynote Jae Lee CEO & Co-founder, TwelveLabs TwelveLabs turns video into knowledge that's usable with foundation models purpose-built for video. With AWS, TwelveLabs trains cutting-edge models that its customers can integrate into workflows—all on one platform—to power some of the world’s heaviest multi-petabyte-scale video AI workloads. --> Watch customer keynote Dean Leitersdorf CEO and Co-founder, Decart Decart, which builds the world’s fastest visual AI systems, is working with AWS to create a new category of generative AI models. Powered by Amazon Trainium 3, these models offer real-time visual intelligence that can understand the world, react to it, and reason with it in real time. --> Watch customer keynote A special Closing Keynote Building the future: The power of the “Renaissance Developer“ Dr. Werner Vogels CTO, amazon.com Discover how developers with curiosity, judgment, and a sense of community are thriving in this age of accelerated invention. By bringing their unique skills and expertise to AI development, these builders are becoming vital to solving complex problems and expanding what’s possible with technology. 2025 Innovation Talks Where cloud innovation meets expert insight Analytics & data Mai-Lan Tomsen Bukovec Vice President, Technology, Data and Analytics, AWS Learn about the latest AWS innovations and how they provide a data and analytics foundation that adapts and evolves to your business and the rapid advancements of AI. Explore emerging trends such as Apache Iceberg adoption, the convergence of analytics and databases, and the evolution of streaming for real-time AI. Discover key architectural patterns for AI-ready data infrastructure as well as new AWS data foundation innovations that make implementation easier. And hear the very latest in data analytics, governance, vector search, and streaming. --> Architecture Shaown Nandi Director of Technology, AWS Discover how agentic AI is reinventing cloud-native architecture, accelerating innovation cycles, and unlocking entirely new application patterns through secure, reasoning-driven agents. Learn how AWS customers are deploying production-ready agents today. Get proven techniques for building agentic applications that autonomously adapt, optimize, and act. And explore the latest AWS capabilities enabling secure, scalable AI agents for enterprise applications, including case studies about how leading customers are leveraging production-ready AI agents. --> Artificial intelligence Pasquale DeMaio Vice President & General Manager of Amazon Connect, AWS The workplace is undergoing a fundamental shift as AI agents become integrated into our daily workflows. In this Innovation Talk, Pasquale DeMaio will explore how organizations can effectively implement AI assistants to enhance employee experience and productivity. Drawing from Amazon's experience with tools like Amazon Q Business and QuickSight, we'll examine real-world examples of AI transforming work patterns. Key principles for building effective AI assistants will be discussed, including leveraging enterprise data, balancing automation with human oversight, designing intuitive AI workspaces, and measuring productivity gains. Attendees will gain a practical framework for evaluating and implementing AI agents in their organizations, focusing on creating value while maintaining security and trust. --> Artificial intelligence Deepak Singh Vice President, Developer Agents & Experiences See how AI-powered tools and autonomous agents are transforming the entire development lifecycle, enabling developers to focus on solving meaningful problems while turning ideas into production-ready applications faster than ever. Explore the integration of generative AI across the development lifecycle. Discover the impact of AI on what developers can build, how they build it, and who can become a developer on AWS. And learn how AWS builds accessible, secure AI tools for developers, emphasizing open-source collaboration and community engagement. --> Artificial intelligence Erin Kraemer Senior Principal Technical Product Manager, AWS Agentic AI Many teams move fast with agentic AI prototypes that impress in demos but stall in production—blocked by gaps in reliability, accuracy, and safety. In this session, AWS agentic AI technical leaders will help builders rethink how to build and scale production-grade, trustworthy agentic AI. Learn proven patterns to build and deploy agents that earn trust in the real world. See AWS agentic AI platform Amazon Bedrock AgentCore in action. Discover how AWS customers move fast from sparks of experiment to scaled AI-driven innovation with trust at the core, transforming industries. --> Cloud operations Nandini Ramani Vice President, Search, Observability, & CloudOps, AWS Discover the ways AWS is innovating cloud operations using AI, ML, generative AI, and AI agents to deliver a more unified and seamless experience for cloud operators, developers, and administrators. See how to build a competitive advantage, move faster, and deliver memorable experiences to customers more easily and securely. Learn how to accelerate operational intelligence, automate compliance, and enhance security. And explore how to speed up your digital transformation and strengthen governance in a dynamic regulatory landscape. --> Compute innovations Willem Visser Vice President, Amazon EC2 Core Platform Barry Cooks Vice President of Compute Abstractions, AWS Explore how customer obsession at AWS drives cloud innovation. Relive the breakthrough moments that revolutionized computing, from EC2 instances to containers and serverless technologies. Learn about global infrastructure and how AWS continues to shape the future of cloud infrastructure for enterprises worldwide. Dive deep into secure, high-performance, cost-effective compute. And learn about designing custom silicon innovation to benefit customers. --> Databases Ganapathy “G2” Krishnamoorthy Vice President of Database Services, AWS Colin Lazier Vice President, AWS Nonrelational Databases, AWS Experience the many ways AWS Databases is transforming data management to be effortless. Explore how databases integrate with AI agents to reduce operational complexity while enabling a new generation of AI-native applications that will advance your business capabilities. Discover how AWS is making databases effortless to migrate, manage, and get value from your data. And learn about the foundation of AWS Databases in the age of agentic AI, and the possibilities of agentic AI apps. --> Financial services Scott Mullins Managing Director, Financial Services, AWS Discover how a more autonomous financial system—defined by innovations like inter-agent payments, real-time underwriting, hyper-personalized customer service, and customized lending offers—represents the industry’s next frontier. Plus hear from two customers who are building the infrastructure for AI systems that independently execute complex financial operations, and learn how they are architecting these systems for compliance and scalability—and what it takes to run autonomous agents in production. --> Learning from Amazon Paul Roberts Director of Technology, AWS Discover how Amazon leaders across Zoox, Prime Video, and Amazon Stores are leveraging AI to power their next-generation innovations with AWS and create better experiences for customers. Explore how customer needs sparked transformative experiences across sports broadcasting, Amazon’s mobile commerce platform, and robotics and automation. And learn AWS best practices to help scale innovation in your organization. --> Migration & modernization Dr. Asa Kalavade Vice President, Migration & Modernization Discover how AWS combines decades of migration expertise with agentic AI to fundamentally transform enterprise modernization. Learn how domain-specific AI agents and partner solutions are making modernization simpler, faster, and more collaborative. See how AI agents continuously learn and automate complex migration tasks, leveraging a new composable framework integrating first- and third-party agents. And get practical steps to modernize your infrastructure and accelerate your organization's AI initiatives. --> Networking & content delivery Robert Kennedy Vice President, Network Services, AWS Learn about the AWS networking innovations that are shaping the future of cloud infrastructure. From our global backbone to AI/ML-optimized data centers, discover breakthrough technologies in content delivery, security, VPC networking, and global connectivity. See how these advancements are enabling customers to build next-generation cloud applications. And explore the reasons why a world-class cloud network is critical for growth, and how AWS ensures its global network infrastructure is scalable, available, high-performance, and secure. --> Public sector Dave Levy Vice President, Worldwide Public Sector, AWS Explore the unique challenges public sector organizations face in digital transformation, from strict security requirements to complex regulatory compliance. See how cloud technology is paving new paths for government agencies and public institutions. Discover practical approaches to secure migration and modernization, and the management of classified and regulated workloads. And learn how organizations are leveraging high-performance computing and implementing AI solutions to advance their missions. --> Security & identity Amy Herzog Vice President and Chief Information Security Officer, AWS AI is helping builders create more, while threat actors expand their efforts. Discover how to adjust your security practice to meet these challenges through real-world examples, and understand the strategies to implement automated protections at scale. Learn how to catch vulnerabilities during development through intelligent automation and how to scale security by embedding expertise in development workflows. Explore how to build adaptive security programs that maintain strong governance. And learn how to reduce developer friction while strengthening protection. --> Storage Andy Warfield Vice President & Distinguished Engineer, AWS Discover breakthrough innovations like S3 Tables for analytics optimization, S3 Vectors for AI workloads, and seamless NAS migration pathways that eliminate storage boundaries and unlock unlimited scalability. Explore Storage for generative AI and agentic AI (S3 Vectors, S3 Express One Zone, and FSx for Lustre delivering enterprise-grade AI workload acceleration). Learn how to break down data silos with a foundational data lake. And hear about the latest storage innovations that maximize data value and operational efficiency. --> Featured Exclusive content at re:Invent Demolish technical debt with AWS Transform We added one final stop for an old, decommissioned server before it heads to the recycling center. Check out this exciting visual demonstration that symbolizes what it is like to demolish tech debt (i.e., manual modernization work) with AWS Transform. --> J.P. Morgan presents ACQUIRED at AWS re:Invent The hosts of the #1 technology show on Spotify and Apple Podcasts took the stage at re:Invent 2025 with special guests to discuss the era of agentic AI, how to maintain innovation at scale, and how AWS helps growing companies emerge as AI leaders and innovators. --> Topics Breakout sessions Analytics --> Watch now Application Integration --> Watch now Architecture --> Watch now Artificial Intelligence --> Watch now Business Applications --> Watch now Cloud Operations --> Watch now Compute --> Watch now Databases --> Watch now Developer Tools --> Watch now End-User Computing --> Watch now Hybrid Cloud & Multicloud --> Watch now Industry Solutions --> Watch now Migration & Modernization --> Watch now Networking & Content Delivery --> Watch now Open Source --> Watch now Security & Identity --> Watch now Serverless & Containers --> Watch now Storage --> Watch now Segments Breakout sessions Developer Community --> Watch now Digital Native Business --> Watch now Enterprise --> Watch now Independent Software Vendor --> Watch now New to AWS --> Watch now Partner Enablement --> Watch now Public Sector --> Watch now Senior Leaders --> Watch now Small & Medium Business --> Watch now Startup --> Watch now Join the AWS Cloud community Thank you for subscribing to re:Invent updates. Follow AWS on social media Learn about AWS What is AWS? AWS blog AWS Merch Store Resources Sponsors Sustainability Help Contact us Code of conduct Terms & conditions Learn about AWS What is AWS? AWS blog AWS Merch Store Resources Sponsors Sustainability Help Contact us Code of conduct Terms & conditions Privacy • Site Terms • Cookie Preferences • © 2025, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:30:39 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.