### Orange Widget Package Setup (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst This `setup.py` file defines a Python package named 'orange-demo' for Orange3 widgets. It uses `setuptools` to find packages and declares an entry point (`orange.widgets`) to register the 'orangedemo' module under the 'Demo' category in the Orange Canvas toolbox. It also specifies Orange3 as a dependency. ```Python # This is a placeholder setup.py for the orange-demo package # In a real package, you would have more details here. from setuptools import setup, find_packages setup( name="orange-demo", version="0.1.0", packages=find_packages(), install_requires=[ "Orange3", ], # Declare Orange3 widgets entry_points={ "orange.widgets": [ "Demo = orangedemo", ], }, ) ``` -------------------------------- ### Verifying Orange Installation (Python) Source: https://github.com/biolab/orange3/blob/master/README-dev.md Imports the Orange package and loads the first row of the Iris dataset to verify that the installation is functional. ```Python import Orange print(Orange.data.Table("iris")[0]) ``` -------------------------------- ### Installing Orange Widget Package (Shell) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst This command installs the Orange widget package from the current directory in editable mode. This allows changes to the code to be reflected without reinstallation. Depending on your Python setup, administrator or superuser privileges might be required. ```Shell pip install -e . ``` -------------------------------- ### Setting up Orange for Development (Python) Source: https://github.com/biolab/orange3/blob/master/README-dev.md Runs the Orange setup script with the 'develop' option, which links the source code into Python's site-packages for easier development. ```Shell python setup.py develop ``` -------------------------------- ### Example: Run Orange3 Translation Script for Slovenian (Shell) Source: https://github.com/biolab/orange3/blob/master/i18n/README.md A concrete example demonstrating how to run the translation script for the Slovenian language ('si'), specifying a typical development path for the Orange source directory. ```Shell ./trans.sh si ~/dev/si/orange3 ``` -------------------------------- ### Starting Orange GUI (Python) Source: https://github.com/biolab/orange3/blob/master/README-dev.md Launches the Orange graphic user interface application from the command line using the Python module execution command. ```Shell python3 -m Orange.canvas ``` -------------------------------- ### Setting Up Full Orange Component Development Environment - Shell Source: https://github.com/biolab/orange3/blob/master/README.md Creates a conda environment named `orange3`, activates it, installs PyQt dependencies, clones the user's forks of `orange-widget-base`, `orange-canvas-core`, and `orange3`, and installs each in editable mode. This setup is required for contributing to the base components of Orange. It's important to install `orange-widget-base` and `orange-canvas-core` before `orange3`. ```Shell conda create python=3.10 --yes --name orange3 conda activate orange3 # Install PyQT and PyQtWebEngine. You can also use PyQt6 pip install -r requirements-pyqt.txt git clone ssh://git@github.com/$MY_GITHUB_USERNAME/orange-widget-base pip install -e orange-widget-base git clone ssh://git@github.com/$MY_GITHUB_USERNAME/orange-canvas-core pip install -e orange-canvas-core git clone ssh://git@github.com/$MY_GITHUB_USERNAME/orange3 pip install -e orange3 # Repeat for any add-on repositories ``` -------------------------------- ### Installing Orange Core Requirements (Pip) Source: https://github.com/biolab/orange3/blob/master/README-dev.md Installs the core Python package dependencies required for Orange from the 'requirements.txt' file using pip. ```Shell pip install -r requirements.txt ``` -------------------------------- ### Installing Orange3 for Development - Shell Source: https://github.com/biolab/orange3/blob/master/CONTRIBUTING.md Instructions for cloning the Orange3 repository and setting up the development environment using `setup.py develop`. This command links the source code directory into the Python site-packages, allowing changes to be reflected without reinstallation. ```Shell git clone https://github.com/biolab/orange3.git cd orange3 python setup.py develop ``` -------------------------------- ### Installing Orange3 with Winget (Windows) Source: https://github.com/biolab/orange3/blob/master/README.md Installs Orange3 on Windows using the winget package manager. Requires winget to be installed and configured. ```Shell winget install --id UniversityofLjubljana.Orange ``` -------------------------------- ### Defining Data Sampler Orange Widget (Part 1) (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst This code defines the basic structure of an Orange Widget named `OWDataSamplerA`. It imports necessary modules, defines the widget's name, description, and icon, and sets up input ('Data') and output ('Sampled Data') channels that handle `Orange.data.Table` objects. The constructor initializes internal state and creates simple GUI elements (labels within an 'Info' box) to display status. ```Python from Orange.widgets.widget import OWWidget, Input, Output from Orange.data import Table import random class OWDataSamplerA(OWWidget): name = "Data Sampler A" description = "Sample 10% of data instances" icon = "icons/data-sampler.svg" class Inputs: data = Input("Data", Table) class Outputs: sample = Output("Sampled Data", Table) want_main_area = False def __init__(self): super().__init__() self.data = None # GUI elements self.info_box = gui.createWidgetBox(self.controlArea, "Info") self.info_label = gui.widgetLabel(self.info_box, "no data yet") self.info_label2 = gui.widgetLabel(self.info_box, "") ``` -------------------------------- ### Implementing Orange Widget GUI and Logic (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst Implements the widget's initialization and core logic. The `__init__` method creates a line edit GUI element bound to the `number` setting and sets up a validator. The `number_changed` method is a callback that sends the current value of the `number` setting through the defined "Number" output channel. ```Python def __init__(self): super().__init__() from AnyQt.QtGui import QIntValidator gui.lineEdit(self.controlArea, self, "number", "Enter a number", box="Number", callback=self.number_changed, valueType=int, validator=QIntValidator()) self.number_changed() def number_changed(self): # Send the entered number on "Number" output self.Outputs.number.send(self.number) ``` -------------------------------- ### Installing Orange GUI Requirements (Pip) Source: https://github.com/biolab/orange3/blob/master/README-dev.md Installs additional Python package dependencies specifically required for the Orange graphic user interface from 'requirements-gui.txt'. ```Shell pip install -r requirements-gui.txt ``` -------------------------------- ### Initializing Orange Widget (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst Implements the initialization method for the "Print" widget. It calls the constructor of the base class `OWWidget` and initializes an internal attribute `self.number` to `None`, preparing the widget to receive input. ```Python def __init__(self): super().__init__() self.number = None ``` -------------------------------- ### Installing PyQt Dependencies with Pip Source: https://github.com/biolab/orange3/blob/master/README.md Installs the required PyQt dependencies for Orange3 when using pip. This command installs PyQt5 and PyQtWebEngine from a requirements file. Alternatively, PyQt6 can be installed using 'pip install PyQt6 PyQt6-WebEngine'. Requires pip and a C/C++ compiler. ```Shell pip install -r requirements-pyqt.txt ``` -------------------------------- ### Checking Code Quality (Linting) - Shell Source: https://github.com/biolab/orange3/blob/master/CONTRIBUTING.md Commands to install development dependencies and run the code linting process using `setup.py lint`. This ensures code conforms to the project's style guidelines before committing. ```Shell pip install -r requirements-dev.txt python setup.py lint ``` -------------------------------- ### Defining an Adder Orange Widget (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst This code defines a simple Orange Widget named 'Adder' that takes two integer inputs ('A' and 'B') and outputs their sum. It uses nested `Inputs` and `Outputs` classes to define channels and decorated methods (`set_A`, `set_B`) to handle input signals. The `handleNewSignals` method performs the addition and sends the result, clearing the output if either input is `None`. ```Python from Orange.widgets.widget import OWWidget, Input, Output class Adder(OWWidget): name = "Add two integers" description = "Add two numbers" icon = "icons/add.svg" class Inputs: a = Input("A", int) b = Input("B", int) class Outputs: sum = Output("A + B", int) want_main_area = False def __init__(self): super().__init__() self.a = None self.b = None @Inputs.a def set_A(self, a): """Set input 'A'.""" self.a = a @Inputs.b def set_B(self, b): """Set input 'B'.""" self.b = b def handleNewSignals(self): """Reimplemeted from OWWidget.""" if self.a is not None and self.b is not None: self.Outputs.sum.send(self.a + self.b) else: # Clear the channel by sending `None` self.Outputs.sum.send(None) ``` -------------------------------- ### Installing Orange3 with Conda Source: https://github.com/biolab/orange3/blob/master/README.md Configures conda channels, creates and activates a new environment, and installs the orange3 package. Requires Miniconda to be installed first. ```Shell # Add conda-forge to your channels for access to the latest release conda config --add channels conda-forge # Perhaps enforce strict conda-forge priority conda config --set channel_priority strict # Create and activate an environment for Orange conda create python=3.10 --yes --name orange3 conda activate orange3 # Install Orange conda install orange3 ``` -------------------------------- ### Importing Orange and Checking Version - Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/index.rst This snippet demonstrates how to import the Orange library in a Python shell and check its installed version to verify a successful installation. ```Python % python >>> import Orange >>> Orange.version.version '3.25.0.dev0+3bdef92' >>> ``` -------------------------------- ### Handling Data Input in Data Sampler Widget (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst This method, decorated with `@Inputs.data`, handles the incoming `Orange.data.Table` signal. It updates the widget's internal data, updates the GUI labels to show input and output instance counts, samples 10% of the input data using `random.sample`, and sends the sampled data (or `None` if the sample size is zero or input is `None`) through the 'Sampled Data' output channel. ```Python @Inputs.data def set_data(self, dataset): """Handle input data.""" self.data = dataset if self.data is not None: self.info_label.setText(f"{len(self.data)} instances in input") # Sample 10% of data sample_size = int(len(self.data) * 0.1) if sample_size > 0: sampled_indices = random.sample(range(len(self.data)), sample_size) sampled_data = self.data[sampled_indices] self.info_label2.setText(f"{len(sampled_data)} instances in output") self.Outputs.sample.send(sampled_data) else: self.info_label2.setText("0 instances in output") self.Outputs.sample.send(None) # Send None if sample size is 0 else: self.info_label.setText("no data yet") self.info_label2.setText("") self.Outputs.sample.send(None) # Clear output if input is None ``` -------------------------------- ### Basic Regression Example in Orange3 (Python) Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/regression.rst Demonstrates the fundamental steps of performing regression in Orange3, including loading data, initializing a regression learner, training a model on the data, and using the trained model to predict values for new instances. ```Python import Orange # Load data data = Orange.data.Table("housing.tab") # Initialize a learner (e.g., Linear Regression) learner = Orange.regression.LinearRegressionLearner() # Train a model model = learner(data) # Predict on new data (using the first instance as an example) instance = data[0] prediction = model(instance) print(f"Actual: {instance.get_class_value()}, Predicted: {prediction}") ``` -------------------------------- ### Constructing Orange Domain with Specific Variables Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.domain.rst Example of creating a new Orange Domain by explicitly defining attribute and class variables using `DiscreteVariable.make` and `ContinuousVariable.make`. ```Python >>> from Orange.data import Domain, DiscreteVariable, ContinuousVariable >>> domain = Domain([DiscreteVariable.make("gender"), ... ContinuousVariable.make("age")], ... ContinuousVariable.make("salary")) >>> domain [gender, age | salary] ``` -------------------------------- ### Defining Orange Widget Input and Metadata (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst Defines a simple Orange widget named "Print" designed to receive input. It specifies the widget's name, description, icon path, and declares a single input channel named "Number" that accepts integer values. It also disables the main area GUI. ```Python from Orange.widgets.widget import OWWidget, Input from Orange.widgets import gui class Print(OWWidget): name = "Print" description = "Print out a number" icon = "icons/print.svg" class Inputs: number = Input("Number", int) want_main_area = False ``` -------------------------------- ### Configuring Orange Widget Layout (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst Configures the layout behavior for the Orange widget. It disables the main area (`want_main_area = False`) and prevents resizing (`resizing_enabled = False`), indicating a simple, fixed-size control-area-only GUI. ```Python # Basic (convenience) GUI definition: # a simple 'single column' GUI layout want_main_area = False # with a fixed non resizable geometry. resizing_enabled = False ``` -------------------------------- ### Defining Orange Widget Metadata (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst Defines the basic structure and metadata for an Orange widget named "Integer Number". It specifies the widget's name, description, icon path, and declares a single output channel named "Number" that transmits integer values. ```Python from Orange.widgets.widget import OWWidget, Output from Orange.widgets.settings import Setting from Orange.widgets import gui class IntNumber(OWWidget): # Widget's name as displayed in the canvas name = "Integer Number" # Short widget description description = "Lets the user input a number" # An icon resource file path for this widget # (a path relative to the module where this widget is defined) icon = "icons/number.svg" # Widget's outputs; here, a single output named "Number", of type int class Outputs: number = Output("Number", int) ``` -------------------------------- ### Setting Up Core Orange Development Environment - Shell Source: https://github.com/biolab/orange3/blob/master/README.md Creates a conda environment named `orange3` with Python 3.10, activates it, clones the user's fork of the `orange3` repository, and installs its PyQt dependencies and the package itself in editable mode. This prepares the environment for working on the core Orange application. ```Shell conda create python=3.10 --yes --name orange3 conda activate orange3 git clone ssh://git@github.com/$MY_GITHUB_USERNAME/orange3 # Install PyQT and PyQtWebEngine. You can also use PyQt6 pip install -r orange3/requirements-pyqt.txt pip install -e orange3 ``` -------------------------------- ### Cloning Orange Source Code (Git) Source: https://github.com/biolab/orange3/blob/master/README-dev.md Command to clone the Orange source code repository from GitHub using the Git version control system. ```Shell git clone https://github.com/biolab/orange3.git ``` -------------------------------- ### Installing Orange3 Add-on with Conda Source: https://github.com/biolab/orange3/blob/master/README.md Installs a specific Orange3 add-on using conda. Replace with the actual name of the add-on. Requires Orange3 to be installed via conda. ```Shell conda install orange3- ``` -------------------------------- ### Defining Orange Widget Setting (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst Declares a widget property named `number` as an Orange `Setting`. This ensures the value of `number` is automatically saved and restored when the workflow is saved or loaded, initializing it with a default value of 42. ```Python number = Setting(42) ``` -------------------------------- ### Example of Three-line Header Format (iris.tab) Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.io.rst This snippet illustrates the three-line header format used in tab-separated data files for Orange. The first line contains feature names, the second line specifies feature types (continuous, discrete), and the third line provides optional flags (e.g., 'class'). Subsequent lines contain the data instances. ```Tab-separated values sepal length sepal width petal length petal width iris continuous continuous continuous continuous discrete class 5.1 3.5 1.4 0.2 Iris-setosa 4.9 3.0 1.4 0.2 Iris-setosa 4.7 3.2 1.3 0.2 Iris-setosa 4.6 3.1 1.5 0.2 Iris-setosa ``` -------------------------------- ### Apply FreeViz Projection in Orange3 Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/projection.rst Illustrates the usage of the FreeViz projection method from Orange.projection. It shows how to create a FreeViz instance, apply it to the Iris dataset, access the calculated components, and get the transformed data. ```Python >>> from Orange.projection import FreeViz >>> from Orange.data import Table >>> iris = Table('iris') >>> freeviz = FreeViz() >>> model = freeviz(iris) >>> model.components_ # FreeViz components array([[ 3.83487853e-01, 1.38777878e-17], [ -6.95058218e-01, 7.18953457e-01], [ 2.16525357e-01, -2.65741729e-01], [ 9.50450079e-02, -4.53211728e-01]]) >>> transformed_data = model(iris) # transformed data >>> transformed_data [[-0.157, 2.053 | Iris-setosa], [0.114, 1.694 | Iris-setosa], [-0.123, 1.864 | Iris-setosa], [-0.048, 1.740 | Iris-setosa], [-0.265, 2.125 | Iris-setosa], ... ] ``` -------------------------------- ### Running Orange Widget with Default Data Input using WidgetPreview - Python Source: https://github.com/biolab/orange3/blob/master/doc/development/source/testing.rst This example demonstrates how to run an Orange widget using WidgetPreview and pass a default data table (e.g., 'iris' dataset) as input. This requires the widget to have a single or default signal handler for the data type. ```Python if __name__ == "__main__": WidgetPreview(OWMyWidgetName).run(Orange.data.Table("iris")) ``` -------------------------------- ### Run Orange3 Translation Script (Shell) Source: https://github.com/biolab/orange3/blob/master/i18n/README.md Execute the translation script located in the i18n directory. This script requires the target language code and the path to the Orange source directory as arguments to perform the translation process. ```Shell ./trans.sh ``` -------------------------------- ### Activating Orange3 Conda Environment Source: https://github.com/biolab/orange3/blob/master/README.md Activates the conda environment named orange3 that was created during the conda installation process. This must be done before running Orange if installed via conda. ```Shell conda activate orange3 ``` -------------------------------- ### Advanced Debugging with WidgetPreview and Manual Signal Sending - Python Source: https://github.com/biolab/orange3/blob/master/doc/development/source/testing.rst This advanced example shows how to gain finer control over debugging by preventing automatic exit (no_exit=True), manually sending signals using the previewer object's send_signals method, and running the widget multiple times. ```Python if __name__ == "__main__": from Orange.classification import RandomForestLearner previewer = WidgetPreview(OWRank) previewer.run(Table("heart_disease.tab"), no_exit=True) previewer.send_signals( set_learner=(RandomForestLearner(), (3, 'Learner', None))) previewer.run() ``` -------------------------------- ### Accessing All Variables in Orange Domain Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.domain.rst Shows how to get a tuple containing all attribute and class variable descriptors from an Orange Domain object. ```Python >>> iris.domain.variables (ContinuousVariable('sepal length'), ContinuousVariable('sepal width'), ContinuousVariable('petal length'), ContinuousVariable('petal width'), DiscreteVariable('iris')) ``` -------------------------------- ### Scoring Features Using Orange Learner Method in Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/preprocess.rst Provides an example of using the score_data() method available in certain Orange learners (like LogisticRegressionLearner) to obtain feature scores as determined by the learning algorithm itself. ```Python learner = Orange.classification.LogisticRegressionLearner() learner.score_data(data) ``` -------------------------------- ### Running Orange Widget with Multiple Inputs to a Single Signal Handler using WidgetPreview - Python Source: https://github.com/biolab/orange3/blob/master/doc/development/source/testing.rst This example shows how to pass multiple inputs to a single signal handler in an Orange widget (OWDataTable) using WidgetPreview. The inputs are provided as a list of tuples, where each tuple contains the data and an associated name. ```Python if __name__ == "__main__": WidgetPreview(OWDataTable).run( [(Table("iris"), "iris"), (Table("brown-selected"), "brown-selected"), (Table("housing"), "housing") ] ) ``` -------------------------------- ### Interactively Rebasing onto Master (Git) Source: https://github.com/biolab/orange3/blob/master/CONTRIBUTING.md Starts an interactive rebase session, applying the commits from the current branch onto the 'master' branch. This allows for editing, reordering, squashing, or dropping commits to clean up the branch history before merging. ```Shell git rebase --interactive master ``` -------------------------------- ### Running Unit Tests - Shell Source: https://github.com/biolab/orange3/blob/master/CONTRIBUTING.md Command to execute the project's unit tests using `setup.py test`. Contributors should ensure all tests pass before submitting changes. ```Shell python setup.py test ``` -------------------------------- ### Continuize with First Value as Base in Orange3 Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/preprocess.rst Sets the `multinomial_treatment` to `Continuize.FirstAsBase`, which creates indicator variables for all values except the first one in the variable's value list. The example shows the resulting data domain. ```Python continuizer.multinomial_treatment = continuizer.FirstAsBase ``` ```Python continuizer(titanic).domain [status=first, status=second, status=third, age=child, sex=male | survived] ``` -------------------------------- ### Defining Multiple Output Channels in Orange Widget (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-channels.rst This snippet demonstrates how to define multiple output channels of the same type within an Orange widget. This setup is used to illustrate concepts like default channels by sending different subsets of data (sampled and remaining) through separate outputs. ```Python class OWDataSamplerC(OWWidget): name = "Data Sampler C" description = "Samples data and outputs sampled and remaining data." icon = "icons/DataSampler.svg" class Inputs: data = Input("Data", Table) class Outputs: sampled_data = Output("Sampled Data", Table) remaining_data = Output("Remaining Data", Table) ``` -------------------------------- ### Creating Orange Instance with Domain Conversion Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.instance.rst Demonstrates creating a new `Orange.data.Instance` from an existing instance but with a different domain. Orange automatically converts the data to fit the new domain, as shown here with a discretized domain. Requires `Orange.data.Instance` and `Orange.preprocess.DomainDiscretizer`. ```Python from Orange.preprocess import DomainDiscretizer discretizer = DomainDiscretizer() d_iris = discretizer(iris) d_inst = Instance(d_iris, inst) ``` -------------------------------- ### Implementing Get Item Method in Orange Storage Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.storage.rst This method allows accessing data rows using standard Python indexing (`[]`). It supports retrieving single rows as `Instance` objects, multiple rows as a new `Storage` object (via slices or sequences), single values as `Value` objects (via row and column indices), or subsets of rows and columns as a new `Storage` object. ```Python __getitem__(self, index) ``` -------------------------------- ### Creating Orange Data Instance Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.instance.rst Demonstrates how to create an `Orange.data.Instance` object. It shows creating an instance with data provided as a list and creating an instance with only a domain, resulting in unknown values. Requires `Orange.data.Table` and `Orange.data.Instance`. ```Python from Orange.data import Table, Instance iris = Table("iris") inst = Instance(iris.domain, [5.2, 3.8, 1.4, 0.5, "Iris-virginica"]) inst inst0 = Instance(iris.domain) inst0 ``` -------------------------------- ### Optimizing compute_value with SharedComputeValue Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.variable.rst Introduces the concept of `SharedComputeValue` for transformations where multiple output variables share computation steps. It provides a partial code example showing the setup for a transformation that divides values by row sums, explaining that using `SharedComputeValue` prevents redundant computation. ```Python iris = Orange.data.Table("iris") def row_sum(data): return data.X.sum(axis=1, keepdims=True) class DivideWithMean(Orange.data.util.SharedComputeValue): ``` -------------------------------- ### Building HTML Documentation (Make) Source: https://github.com/biolab/orange3/blob/master/CONTRIBUTING.md Executes the 'make html' command, which typically triggers the build process for HTML documentation using a Makefile. This command should be run from within the specific documentation part directory. ```Shell make html ``` -------------------------------- ### Handling Number Input in Orange Widget (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial.rst This method handles the input signal named 'number'. It updates the widget's internal state (`self.number`) and the displayed label based on the input value. It specifically checks for `None`, which indicates a disconnected or cleared input channel. ```Python @Inputs.number def set_number(self, number): """Set the input number.""" self.number = number if self.number is None: self.label.setText("The number is: ??") else: self.label.setText("The number is {}".format(self.number)) ``` -------------------------------- ### Instantiating PyQt Widgets (Preferred) - Python Source: https://github.com/biolab/orange3/blob/master/CONTRIBUTING.md Demonstrates the preferred method for instantiating PyQt widgets by passing static property values directly as keyword arguments to the constructor. This is recommended over calling separate setter methods after instantiation. ```Python view = QListView(alternatingRowColors=True, selectionMode=QAbstractItemView.ExtendedSelection) ``` -------------------------------- ### Implementing Orange3 Settings Migration (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-settings.rst This Python function demonstrates how to implement the `migrate_settings` method in an Orange3 widget. It checks the old settings `version` and applies necessary transformations (like scaling a proportion value) to the `settings` dictionary to make them compatible with the current widget version. ```python def migrate_settings(settings, version): if version < 2: if "proportion" in settings: settings["proportion"] = settings["proportion"] / 100 ``` -------------------------------- ### Setting Qt Property via Keyword Argument (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/gui.rst Demonstrates how to set a property on a Qt control created using the `Orange.widgets.gui` library by passing it as a keyword argument during initialization. This is shown to be equivalent to calling the corresponding setter method after creation. ```Python cb = gui.comboBox(..., editable=True) ``` ```Python cb = gui.comboBox(...) cb.setEditable(True) ``` -------------------------------- ### Constructing Orange Domain from Existing Domain Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.domain.rst Shows how to create a new Orange Domain by selecting variables from an existing domain and adding new ones, using the `source` parameter. ```Python >>> new_domain = Domain(["sepal length", ... "petal length", ... DiscreteVariable.make("color")], ... iris.domain.class_var, ... source=iris.domain) >>> new_domain [sepal length, petal length, color | iris] ``` -------------------------------- ### Iterating Through Dataset Instances - Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/data.rst Demonstrates how to iterate through the first three instances (rows) of the Orange dataset and print each instance. ```Python for d in data[:3]: print(d) ``` -------------------------------- ### Remove Discrete Variables During Continuization in Orange3 Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/preprocess.rst Sets the `multinomial_treatment` to `Continuize.Remove`, which removes all discrete variables from the data. The example shows the resulting data domain containing only the class variable. ```Python continuizer.multinomial_treatment = continuizer.Remove ``` ```Python continuizer(titanic).domain [ | survived] ``` -------------------------------- ### Handling Data Input and Context in Orange Widget (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-settings.rst Demonstrates the typical structure of a data signal handler (`set_data`) in an Orange widget, showing the correct placement for calling `closeContext()` before processing new data and `openContext()` after processing to manage context-dependent settings based on the input data's domain. ```Python @Input.data def set_data(self, data): self.closeContext() self.data = data self.graph.setData(data) self.initAttrValues() if data is not None: self.openContext(data.domain) self.updateGraph() self.sendSelections() ``` -------------------------------- ### Using and Demonstrating Timed Wrapper Learner - Python Source: https://github.com/biolab/orange3/blob/master/tutorials/learners.ipynb Shows how to instantiate and use the `TimedLearner` wrapper. It wraps the standard `Orange.regression.LinearRegressionLearner`, fits it twice on the 'housing' dataset, and prints the `time` attribute of the resulting model objects and the cumulative `time` attribute of the `TimedLearner` instance to demonstrate the time measurement functionality. ```Python tl = TimedLearner(Orange.regression.LinearRegressionLearner()) m1 = tl(housing) print(m1.time) m2 = tl(housing) print(m2.time) print(tl.time) ``` -------------------------------- ### Constructing Continuous Domain with Orange Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/preprocess.rst Demonstrates how to use Orange.preprocess.DomainContinuizer to convert a dataset's domain, replacing discrete attributes with continuous ones. It shows the basic instantiation and application of the continuizer to a dataset. ```Python domain_continuizer = Orange.preprocess.DomainContinuizer() domain1 = domain_continuizer(titanic) ``` -------------------------------- ### Setting I/O Summaries in Orange3 Widget Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-utilities.rst Shows how to set input and output summaries for an Orange3 widget using the `self.info` namespace and the `set_input_summary` and `set_output_summary` methods. These summaries appear in the widget's status bar and can be simple strings or predefined constants like `self.info.NoInput` and `self.info.NoOutput`. ```Python self.info.set_input_summary("foo") self.info.set_output_summary("bar") # Using predefined constants self.info.set_input_summary(self.info.NoInput) self.info.set_output_summary(self.info.NoOutput) ``` -------------------------------- ### Instantiating PyQt Widgets (Avoid) - Python Source: https://github.com/biolab/orange3/blob/master/CONTRIBUTING.md Demonstrates an discouraged method for instantiating PyQt widgets where properties are set using separate setter methods after the object is created. The preferred method is to pass these values as keyword arguments to the constructor (see previous snippet). ```Python view = QListView() view.setAlternatingRowColors(True) view.setSelectionMode(QAbstractItemView.ExtendedSelection) ``` -------------------------------- ### Defining Widget GUI Controls with Orange.widgets.gui (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-settings.rst Uses functions from the `Orange.widgets.gui` module to construct the user interface within the widget's control area. This snippet demonstrates adding a separator, creating a group box for options, and adding a spin box and a check box. These controls are bound to the persistent settings variables (`self.proportion`, `self.commitOnChange`) and callbacks are specified for value changes. The options box is initially disabled. ```Python gui.separator(self.controlArea) self.optionsBox = gui.createGroupBox(self.controlArea, "Options") # Assuming self.optionsBox is a QLayout or QWidget gui.spin(self.optionsBox, self, 'proportion', 1, 100, 1, label="Sample Size:", callback=[self.sampleData, self.checkCommit]) gui.checkBox(self.optionsBox, self, 'commitOnChange', "Commit data on selection change") # Disable controls initially self.optionsBox.setDisabled(True) ``` -------------------------------- ### Remove Multinomial Variables During Continuization in Orange3 Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/preprocess.rst Sets the `multinomial_treatment` to `Continuize.RemoveMultinomial`, which removes discrete variables with more than two values. Binary variables are treated using the `FirstAsBase` strategy. The example shows the resulting data domain. ```Python continuizer.multinomial_treatment = continuizer.RemoveMultinomial ``` ```Python continuizer(titanic).domain [age=child, sex=male | survived] ``` -------------------------------- ### Continuize with Most Frequent Value as Base in Orange3 Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/preprocess.rst Sets the `multinomial_treatment` to `Continuize.FrequentAsBase`, using the most frequent value in the data as the base for indicator variables. This requires data to calculate frequencies. The example shows the resulting data domain. ```Python continuizer.multinomial_treatment = continuizer.FrequentAsBase ``` ```Python continuizer(titanic).domain [status=first, status=second, status=third, age=child, sex=female | survived] ``` -------------------------------- ### Changing Directory to Documentation Part (Shell) Source: https://github.com/biolab/orange3/blob/master/CONTRIBUTING.md Changes the current working directory to a specific subdirectory within the 'doc' folder. Replace '' with the name of the documentation section you want to build (e.g., 'data-mining-library', 'development', 'visual-programming'). ```Shell cd doc/ ``` -------------------------------- ### Applying Specific Discretization Method in Orange3 (Python) Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/preprocess.rst Demonstrates how to specify a particular discretization algorithm, such as Equal Frequency with 4 bins, when applying discretization to an Orange3 data table by passing a method instance to the constructor. ```Python import Orange.data import Orange.preprocess from Orange.preprocess.discretize import EqualFreq table = Orange.data.Table("iris.tab") discretizer = Orange.preprocess.Discretize(method=EqualFreq(n=4)) discretized_table = discretizer(table) print("Original table:") print(table) print("\nDiscretized table (EqualFreq):") print(discretized_table) ``` -------------------------------- ### Continuize Discrete Variables as Normalized Ordinal in Orange3 Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/preprocess.rst Sets the `multinomial_treatment` to `Continuize.AsNormalizedOrdinal`, treating multinomial variables as ordinal and replacing them with a single continuous variable scaled to the range [0, 1]. The example shows the representation of specific data instances. ```Python continuizer.multinomial_treatment = continuizer.AsNormalizedOrdinal ``` ```Python titanic1 = continuizer(titanic) ``` ```Python titanic1[700] [1.000, 0.000, 1.000 | no] ``` ```Python titanic1[15] [0.333, 0.000, 1.000 | yes] ``` -------------------------------- ### Creating and Printing Orange Table from NumPy - Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/data.rst Creates an Orange `Table` object from a defined `domain`, a feature matrix `X`, and a metadata matrix `M` using the `Table.from_numpy` constructor. The resulting table is then printed to the console. ```Python table = Table.from_numpy(domain, X=X, metas=M) print(table) ``` -------------------------------- ### Collect Orange3 Messages for Translation (trubar) Source: https://github.com/biolab/orange3/blob/master/i18n/README.md This command uses the `trubar` tool to collect translatable strings from the Orange source code and update the specified message file. Obsolete messages are removed and new ones are added, requiring manual translation or marking. ```Shell trubar collect -s Orange i18n/si/msgs.jaml ``` -------------------------------- ### Creating Orange Table with Custom Domain (Python) Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/data.rst Demonstrates how to create an Orange Table from a NumPy array while specifying a custom domain with meaningful feature names. Requires defining the domain using Orange.data.Domain and variable types. Requires NumPy and the Orange library. ```Python >>> domain = Orange.data.Domain([Orange.data.ContinuousVariable("lenght"), ... Orange.data.ContinuousVariable("width")]) >>> data = Orange.data.Table(domain, X) >>> data.domain [lenght, width] ``` -------------------------------- ### Using Multiple Message Classes in Orange3 Widget Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-utilities.rst Provides examples of how to trigger, conditionally show, format, and clear messages defined within nested message classes. Messages are issued by accessing the class attribute (e.g., `self.Error.no_continuous_features()`) and can accept arguments for formatting or the `shown` flag. ```Python self.Error.no_continuous_features() self.Warning.no_scissors_run() # Conditionally show self.Warning.no_scissors_run(shown=self.scissors_are_available) # With formatting self.Warning.ignoring_discrete(", ".join(attrs), n=len(attr)) # Clear a specific message self.Warning.ignoring_discrete.clear() # Clear all messages of a type self.Warning.clear() # Clear all messages of all types self.clear_messages() ``` -------------------------------- ### Implementing OWDataSamplerC selection Method (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-channels.rst This snippet shows the implementation of the `selection` method within the `OWDataSamplerC` widget. This method is typically responsible for handling user interactions that result in a data selection or subset. ```Python def selection(self, selection): # Method body for handling selection pass # Replace with actual implementation ``` -------------------------------- ### Continuize Discrete Variables as Ordinal in Orange3 Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/preprocess.rst Sets the `multinomial_treatment` to `Continuize.AsOrdinal`, treating multinomial variables as ordinal and replacing them with a single continuous variable representing the index of the value (0, 1, 2...). The example shows the representation of a specific data instance. ```Python continuizer.multinomial_treatment = continuizer.AsOrdinal ``` ```Python titanic1 = continuizer(titanic) ``` ```Python titanic[700] [third, adult, male | no] ``` ```Python titanic1[700] [3.000, 0.000, 1.000 | no] ``` -------------------------------- ### Comment on Viewing Built Documentation (Shell) Source: https://github.com/biolab/orange3/blob/master/CONTRIBUTING.md A comment indicating the location of the generated HTML documentation entry point after the build process is complete. The 'index.html' file in the 'build/html' subdirectory is the main file to open in a web browser. ```Shell # Now open build/html/index.html to see it ``` -------------------------------- ### Declaring Orange3 Widget Settings (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-settings.rst This snippet shows how to declare widget settings within an Orange3 widget class definition. It includes declaring a `DomainContextHandler` for context-aware settings and defining standard `Setting` and `ContextSetting` attributes with default values. ```python settingsHandler = DomainContextHandler() attr_x = ContextSetting("") attr_y = ContextSetting("") auto_send_selection = Setting(True) toolbar_selection = Setting(0) color_settings = Setting(None) selected_schema_index = Setting(0) ``` -------------------------------- ### Creating a Data Domain - Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/data.rst Creates a data domain specifying the types and roles of variables. Defines a continuous variable, a discrete variable with values, and a string variable as a meta variable. ```Python domain = Domain([ContinuousVariable("col1"), DiscreteVariable("col2", values=["red", "blue"])], metas=[StringVariable("col3")]) ``` -------------------------------- ### Randomly Sample Data Instances (Rows) in Orange3 Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/data.rst This snippet demonstrates how to create a new Orange3 data table containing a random sample of instances (rows) from an existing table. It uses `random.sample` to select a specified number of instances and constructs a new `Orange.data.Table` with the original domain and the sampled instances. ```Python >>> sample = Orange.data.Table(data.domain, random.sample(data, 3)) >>> sample [[6.000, 2.200, 4.000, 1.000 | Iris-versicolor], [4.800, 3.100, 1.600, 0.200 | Iris-setosa], [6.300, 3.400, 5.600, 2.400 | Iris-virginica] ] ``` -------------------------------- ### Discretizing Data and Accessing Variable Descriptor in Orange (Python) Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.variable.rst This snippet shows how to apply discretization to an Orange Table using `Orange.preprocess.DomainDiscretizer`. It creates a discretizer instance, applies it to the `iris` table to get `d_iris`, and then accesses the descriptor of the first variable in the discretized table, showing its new name and discrete values. ```Python >>> from Orange.preprocess import DomainDiscretizer >>> discretizer = DomainDiscretizer() >>> d_iris = discretizer(iris) >>> d_iris[0] DiscreteVariable('D_sepal length') >>> d_iris[0].values ['<5.2', '[5.2, 5.8)', '[5.8, 6.5)', '>=6.5'] ``` -------------------------------- ### Include Core Requirements (Requirements File) Source: https://github.com/biolab/orange3/blob/master/requirements.txt Specifies that the core project dependencies listed in 'requirements-core.txt' should be included. ```Requirements File -r requirements-core.txt ``` -------------------------------- ### Importing Domain Classes - Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/data.rst Imports the necessary classes (Domain, ContinuousVariable, DiscreteVariable, StringVariable) from the Orange.data module to define a data domain. ```Python from Orange.data import Domain, ContinuousVariable, DiscreteVariable, StringVariable ``` -------------------------------- ### Loading Table and Accessing Domain in Orange Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.domain.rst Demonstrates loading a dataset into an Orange Table and accessing its domain descriptor, which lists the features and class variables. ```Python >>> from Orange.data import Table >>> iris = Table("iris") >>> iris.domain [sepal length, sepal width, petal length, petal width | iris] ``` -------------------------------- ### Train and Predict with Mean Regression (Python) Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/regression.rst Illustrates the usage of the Mean Regression learner in Orange3. It covers loading data, initializing the MeanLearner, training a model on the entire dataset, and predicting values for multiple data instances, showing the constant mean output. ```Python from Orange.data import Table from Orange.regression import MeanLearner data = Table('auto-mpg') learner = MeanLearner() model = learner(data) print(model) print(model(data[:4])) ``` -------------------------------- ### Loading Data with Orange.data.Table - Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/data.rst Imports the Orange library and loads a dataset named 'lenses' using the Orange.data.Table class. Orange automatically checks for readable file types. ```Python import Orange data = Orange.data.Table("lenses") ``` -------------------------------- ### Using Orange Instance Utility Functions (get_class, attributes) Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.instance.rst Illustrates using utility methods of an `Orange.data.Instance`. `get_class()` retrieves the class value, and `attributes()` provides an iterator over the attribute values. Requires an existing `Instance` object. ```Python inst.get_class() for e in inst.attributes(): print(e) ``` -------------------------------- ### Training and Predicting with Logistic Regression in Orange3 Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/classification.rst This snippet shows the basic workflow for classification in Orange3. It loads data, initializes a `LogisticRegressionLearner`, trains a `classifier` using the data, and then uses the classifier to predict the class indices for the first three data instances. ```Python import Orange data = Orange.data.Table("voting") learner = Orange.classification.LogisticRegressionLearner() classifier = learner(data) classifier(data[:3]) ``` -------------------------------- ### Accessing Orange Instance Data (x, y, metas) Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/reference/data.instance.rst Shows how to access the attribute values (`x`), class values (`y`), and meta attribute values (`metas`) of an `Orange.data.Instance` using its respective properties. Requires an existing `Instance` object. ```Python inst.x inst.y inst.metas ``` -------------------------------- ### Setting Output Summary with Details Orange3 Python Source: https://github.com/biolab/orange3/blob/master/doc/development/source/widget.rst Sets the output summary using individual components: a brief string, an optional detailed string, an optional QIcon, and an optional Qt.TextFormat. Provides flexibility in defining the output state description. ```Python set_output_summary(brief:str, detailed:str=\"\", \ icon:QIcon=QIcon, format:Qt.TextFormat=Qt.PlainText) ``` -------------------------------- ### Comparing Multiple Regressors in Orange3 (Python) Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/regression.rst Illustrates how to initialize and use different regression algorithms available in Orange3, including Linear Regression, Random Forest, and Ridge Regression. It trains these models on a dataset and demonstrates how to make predictions on specific data instances, comparing the results. ```Python import Orange # Load data data = Orange.data.Table("housing.tab") # Define a list of learners learners = [ Orange.regression.LinearRegressionLearner(), Orange.regression.RandomForestLearner(), Orange.regression.RidgeRegressionLearner() ] # Train models and predict for the first 5 instances print(" y linreg rf ridge") for i in range(5): instance = data[i] actual = instance.get_class_value() predictions = [learner(data)(instance)[0] for learner in learners] print(f"{actual:5.1f} {predictions[0]:5.1f} {predictions[1]:5.1f} {predictions[2]:5.1f}") ``` -------------------------------- ### Include Documentation Requirements (Requirements File) Source: https://github.com/biolab/orange3/blob/master/requirements.txt Specifies that the documentation-specific dependencies listed in 'requirements-doc.txt' should be included. This is indicated as being for ReadTheDocs. ```Requirements File -r requirements-doc.txt ``` -------------------------------- ### Initializing ProgressBar Class in Orange3 Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-utilities.rst Demonstrates how to initialize the `ProgressBar` class from `Orange.widgets.gui` within an Orange3 widget, typically used to indicate progress for iterative operations. The constructor requires the widget instance (`self`) and the total number of iterations (`n`). ```Python progress = Orange.widgets.gui.ProgressBar(self, n) ``` -------------------------------- ### Loading and Inspecting Data in Orange3 Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/classification.rst This snippet demonstrates how to load a dataset using `Orange.data.Table`, specifically the "voting" dataset. It then accesses and displays the first data instance (`data[0]`), showing its features and class label. ```Python import Orange data = Orange.data.Table("voting") data[0] ``` -------------------------------- ### Setting Input Summary with Details Orange3 Python Source: https://github.com/biolab/orange3/blob/master/doc/development/source/widget.rst Sets the input summary using individual components: a brief string, an optional detailed string, an optional QIcon, and an optional Qt.TextFormat. Provides flexibility in defining the input state description. ```Python set_input_summary(brief:str, detailed:str=\"\", \ icon:QIcon=QIcon, format:Qt.TextFormat=Qt.PlainText) ``` -------------------------------- ### Defining Multi-Input Channels in Orange Widget (Python) Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-channels.rst This snippet shows how to define input and output channels for an Orange widget. It highlights the use of the `multiple=True` argument for an input channel, allowing it to accept connections from multiple source widgets. ```Python class OWLearningCurveA(OWWidget): name = "Learning Curve A" description = "Test learning algorithms on varying training set sizes." icon = "icons/LearningCurve.svg" class Inputs: data = Input("Data", Table) learner = Input("Learner", Learner, multiple=True) class Outputs: scores = Output("Scores", Table) points = Output("Points", Table) ``` -------------------------------- ### Randomly Sample Attributes (Columns) in Orange3 Python Source: https://github.com/biolab/orange3/blob/master/doc/data-mining-library/source/tutorial/data.rst This snippet demonstrates how to create a new Orange3 data table with a random subset of attributes (columns). It samples attributes using `random.sample`, creates a new `Orange.data.Domain` with the selected attributes and the original class variable, and then constructs a new `Orange.data.Table` using the new domain and the original data. ```Python >>> atts = random.sample(data.domain.attributes, 2) >>> domain = Orange.data.Domain(atts, data.domain.class_var) >>> new_data = Orange.data.Table(domain, data) >>> new_data[0] [5.100, 1.400 | Iris-setosa] ``` -------------------------------- ### Using Simple Messages in Orange3 Widget Source: https://github.com/biolab/orange3/blob/master/doc/development/source/tutorial-utilities.rst Shows how to display simple information, warning, or error messages directly using methods like `self.error()`, `self.warning()`, and `self.information()`. Messages can be set, replaced, cleared by setting an empty string, or conditionally shown/hidden using the `shown` argument. ```Python self.warning("Discrete features are ignored.") self.error("Fitting failed due to missing data.") # This replaces the old error message self.error("Fitting failed due to weird data.") # Remove a message self.error() # Conditionally show/hide self.error("No suitable features", shown=not self.suitable_features) ```